Posting a File using the WebBrowser Class
February 12th, 2009
2 comments
So you have a WebBrowser object in .NET that you would like to use to automatically post a file to a given location? You can probably figure out how to set values on this page:
<input type="text" name="myTextField">
// Update myTextField with a value
webBrowser.Document.All["myTextField"].SetAttribute("value", "I set your value");
But how do you update this?
<input type="file" name="myFileField">
You can’t simply use the SetAttribute function, as there is no attribute to correctly set; this was done intentionally to prevent users from using shady Javascript to automatically capture and send files from a page. So how do you do it? Something even more shady:
HtmlElement element = webBrowser.Document.GetElementById("myFileField");
element.Focus();
System.Threading.Thread.Sleep(1000);
// Perform SendKeys to fake the browser into setting the file name
SendKeys.SendWait(@"C:\Path To My File\test.txt");
SendKeys.Flush();
I hope that Google picks this up and saves someone else the thirty minutes worth of their life that I wasted attempting to figure out a solution.