How to write in the input field of a type file on a web page programmatically from a C # windows application using mshtml?

I have a C # windows application project that should open IE, go to the site, log in and upload some files.

I used the shDocvW and mshtml libraries for this. I can open IE, go to the site and log in, but I cannot upload files.

I can go to the website and then add a text value to the input fields (this is a text input field) on the website using

HTMLInputElement txtbox1 =(HTMLInputElement)oDoc.all.item("login", 0); txtbox1.value = "Login_name"; 

I could even add a text value to the password input field. After I entered the site, I need to upload a file.

The problem I am facing is that I cannot add a path (line) to the input field of type "file".

I can not find any solutions.

+4
source share
2 answers

I tried many ways to do this, but that was not possible because IE8 made the Value property read-only for security reasons.

Ok, I found a job. It is very simple, but using SendKeys not always considered the best software solution. But he does the job.

 oBrowser.Navigate("http://www.some-url.com", ref oNull, ref oNull, ref oNull, ref oNull); while (oBrowser.Busy) { System.Threading.Thread.Sleep(20); } //Locate the Input element of type="file" HTMLInputElement file_1 = (HTMLInputElement)oDoc.all.item("file_1", 0); file_1.select(); SendKeys.Send("{TAB}"); //Navigate to the Browse button SendKeys.Send(" "); //Click on the browse button SendKeys.Send(@"c:\Test.txt"); //File Path SendKeys.Send("{TAB}"); SendKeys.Send("{ENTER}"); 

This code can be improved by checking the active window and possibly setting the correct value before each SendKeys command. This can be done using FindWindow() and FindWindowEx() of user32.dll . These methods in the window APIs are used to search for the active window and child windows.

+4
source

Does your implementation affect the use of IE? It might be easier with the WebClient class to upload a file using a POST request, but it depends on whether the form supports any other actions after submitting. If not, you can use WebClient.UploadFile .

If you need to load several POST values ​​for this form (for example, a new file name?), Look here: WebClient.UploadFile and WebClient.UploadValues ​​in the same call

+2
source

All Articles