I am trying to upload files into a website using selenium which when Clicked on Choose file opens a Native windows, so for this purpose I have been using AutoIT which seems not very reliable when I go for parallel execution. Since I am using Selenium with C# I thought of finding some solution through which I can handle that Native window but I am unable to find any solution please can anybody tell me some reliable way to do this particular automation.
2 Answers
This worked for me so hopefully it'll work for you. I use it in an extension method here, but you can use as/in a normal method. So this uses C# libraries to enter the path in the dialog and presses enter when done.
string idPath = "C:/text.txt"; //Path to the file you are trying to upload
var button = driver.FindElement(By.Id("blah"));
button.Click()
driver.WaitOnAPage(1); //simple wait method
SendKeys.SendWait(@idPath); //this code sends the path to the file upload dialog
CommonMethods.WaitOnAPage(1);//simple wait method
SendKeys.SendWait(@"{Enter}"); //simulates pressing enter button
5 Comments
Piyush
No able to exactly understand what are you trying to do here. If possible could you please elaborate some more with more comment which window are you trying to handle here.
marwaha.ks
So the code above sends the path to the file dialog once the dialog is open and the presses enter (instead of clicking on the 'OK' button). I shall edit it to make it more apparent
Piyush
Thank you very much sir this one worked very nicely. Just one more to ask here how much feasible will be this method in case of Parallel execution.
marwaha.ks
Yeah it will work as it doedn't depend on anything other than the file path existing.
Ger Mc
Important to add, this requires the System.Windows.Forms assembly reference
There are multiple ways to go on this:
IWebElement element = driver.FindElement(By.Id("your_path_to_file_here"));
element.SendKeys("C:\\Some_Folder\\MyFile.txt");
Using IJavaScriptExecutor:
IWebElement element = driver.FindElement(By.Id("your_path_to_file_here"));
string script = "arguments[0].value='" + "C:\\\\temp\\\\file.txt" + "';";
((IJavascriptExecutor)driver).executeScript(script, element);
Both options insert the text directly in your file path input and afterwards you can just click the Upload button.
1 Comment
Piyush
This won't work in this case since it is developed in such a way that when file file is selected I don't see any change in DOM and also I don't see anywhere. Instead after I select the file textbox shows only the filename and not the complete path.