'c# selenium to browse and upload a file

In my selenium c# windows forms application, I have a scenario like uploading a doc/docx file. I have already done uploading in some another case.since it has some text box infront of browse button I uploaded using

IWebElement element = driver.FindElement(By.Id("uploadhere"));
element.SendKeys("C:\\Some_Folder\\MyFile.txt");

But here now in my present scenario, I cant use this code. My picture below shows the upload file dialog box. I googled many and couldnt find one that suits my need...I can click on browse button but cant select a file. Firebug and selenium IDE seemed not to be useful..

Can anyone help me on this? Any comments would be really appreciated..enter image description here



Solution 1:[1]

Since its a OS dialog box you cannot handle it with selenium , you can use java script executor check this link Webdriver: File Upload

Solution 2:[2]

You can use windows forms commands to navigate the upload box that appears. I handled it by using keys to change the focus of the window to where I need it and send a string with the path to the file I wanted to upload. See code below:

//Click browse btn to open upload window
     driver.FindElement(By.ClassName("uploadbtn")).Click();

//Wait for Upload Window to appear(may not be necessary in some cases)
     Thread.Sleep(2000);

//Send the path and then click the Right arrow key
     SendKeys.SendWait(GetProjectRoot() + @"\DataFiles\red.png" + @"{RIGHT}");

//Click Enter Key to submit
     SendKeys.SendWait(@"{Enter}");

Be mindful if you are using a console application, there are some steps you would need to do to get "using System.Windows.Forms;" to work. The idea is to use the keys to navigate the upload window. This method also only works if you have the path to the file you need to upload.

Solution 3:[3]

We can Not handle windows fileOpenDialog through Selenium. we have to use either Javascript executor but some time still it is not possible to use Javascriptexecutor. it won't execute. It gives null value error. Example :

If you go to naukri.com on below link http://my.naukri.com/manager/createacc2.php?othersrcp=11499&wExp=N or

<input type="file" id="browsecv" name="browsecv"></input>

to upload the file.

your javascript and selenium wont identify the browse element.

Then we have to use third party tool such as Point Position to compute x & Y coordinate of "browsefile" Button then, we can use C#.Net low level MouseClick handle to click on it or we can use AutoIt tool to handle wondows pop. To know more you can visit on

http://avinashpandeblogsonseleniumautomation.blogspot.in/2015/06/upload-file-using-selenium-web-driver.html you will get solution with an example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Isaac M
Solution 3 Avinash Pande