Search code examples
c#mshtml

How to write to a input field of type file in a web page programatically from a c# windows app using mshtml?


I have a c# windows app project which has to open IE, navigate to a website, login and then upload a few files.

I used shDocvW and mshtml libraries to do this. I am able to open IE, navigate to the website and login but am not able to upload the files.

I am able to navigate to the website and then add a text value to the input fields(This is an input field of type "text") on the website using -

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

I also was similarly able to even add a text value to the input field of type "password". After I logged in to the website, I have to upload a file.

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

I am not able to find any solutions.


Solution

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

    Well, I did find a work around. It is very simple but the use of SendKeys is not always considered the best programming solution. But, it 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 bettered by checking for the active window and perhaps setting the correct one before every SendKeys command. This can be done by using the FindWindow() and FindWindowEx() of user32.dll. These methods in the windows API are used to find the active window and the child windows.