Webdriver - Upload file using C#
We will look at two ways to upload a file in Selenium WebDriver - one is uploading a file using AutoIt and second is uploading a file using SendKeys.
Example 1 - Uploading a File using AutoIt
Download AutoIt and Install it.
Install AutoIt. Below are the screenshots I took during AutoIt installation.
I have used the below web page to upload the file. Below I have right-clicked on the Browse button and selected "Inspect Element". You can use any other web page to upload the file and obviously change the dependent lines in the code accordingly.
Create a new test in Visual Studio.
Add References: WebDriver, WebDriver.Support, AutoltX3Lib.
Write the below code:
Using Firefox we are opening our html page where we need to upload the file. Then we are finding the Browse button and clicking on it in order to open File Upload dialog. Create a new interface for AutoItX3 and then use it to access the methods/ properties of AutoItX3. With au3.ControlFocus we are setting the focus on the File name field of the File Upload dialog. With au3.ControlSetText we are giving path of the file to be uploaded i.e. pasting the filename (along with path) in the File name field. At last we are clicking on the Open button.
You can find more about AutoIt methods like ControlFocus, ControlSetText & ControlClick.
For passing parameters to functions like ControlFocus etc. you can use AutoIt Window Info. Its like an Object Spy in QTP/UFT. I have added parameters like "File Upload", "Edit1" etc. using this.
After running the code, the upload file page will be shown like below:
Example 2 - Uploading a File using SendKeys
For SendKeys to work make sure you add "System.Windows.Forms" in references and also add it in the code.
Here, using Firefox we are opening our html page where we need to upload the file. Then we are finding the Browse button and clicking on it in order to open File Upload dialog.
SendKeys.SendWait method actually sends the given keys to the active application, and then waits for the messages to be processed. Here we are sending the filename (along with path) to be uploaded and then hitting Enter key.