Tuesday, October 21, 2014

Upload File In Selenium Webdriver In C#

Many web applications contain HTML forms which interact with the user. The user is able to enter data in to the form fields and submit the data to a server. Selenium is able to handle form inputs such as entering text in text fields, selecting radio buttons, selecting a value from a drop-down menu and so on. Things get a little tricky when dealing with input form fields of type “file”, to allow users to browse for a file and attach the file to the HTML form and submit the file.

We can upload file in selenium webdriver easily. We have to just find the element with file control, open the widow popup, select the file and then set the value of document we want to upload in it.

Complete example in C#.Net to upload the document using selenium webdriver.

using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.PageObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public class UtilityManageRateSheetsPage
{
public void UploadFile(string fileToUpload)
        {           
                //Open window popup
                IWebElement upload = Browser.WebDriver.FindElement(By.XPath("/html/body/div[2]/div/table/tbody/tr[1]/td[3]/div/form/input[1]"));                       
                Actions actions = new Actions(Browser.WebDriver);
                actions = actions.MoveToElement(upload);
                actions = actions.Click();
                actions.Build().Perform();
                System.Threading.Thread.Sleep(1000);
                //Select the file
                System.Windows.Forms.SendKeys.SendWait(fileToUpload);
                System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                System.Threading.Thread.Sleep(1000);
                //Click import button
                Browser.WebDriver.FindElement(By.XPath("/html/body/div[2]/div/table/tbody/tr[1]/td[3]/div/form/input[2]")).Click();
                //Wait for the file to be uploaded
                 System.Threading.Thread.Sleep(10000);  
       }

}

Popular Posts