Arjun
Arjun

Reputation: 1069

Submit html form via Window form

I need to automize login process of a widsite. After googling for a while, I wrote this code. But the problem is after running this code, no errors, no output. I am unable to know where I went wrong.

private void Form1_Load(object sender, EventArgs e)

        {
            WebBrowser browser = new WebBrowser();
            string target = "http://authcisco/auth.html";
            browser.Navigate(target);
            browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Credentials);   
}
private void Credentials(object sender, WebBrowserDocumentCompletedEventArgs e)

        {
            WebBrowser b = (WebBrowser)sender;
            b.Document.GetElementById("userName").SetAttribute("value", "shyam");
            b.Document.GetElementById("pass").SetAttribute("value", "shyam");
            b.Document.GetElementById("Submit").InvokeMember("click");  

        }  

Thank You.

Upvotes: 0

Views: 240

Answers (1)

Joey
Joey

Reputation: 354536

I'd say it'd be easier to use an HttpWebRequest instead of automating a browser instance.

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://authcisco/auth.html");
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
string content = string.Format("userName={0}&pass={1}", HttpUtility.UrlEncode(Username), HttpUtility.UrlEncode(Password));
byte[] data = System.Text.Encoding.ASCII.GetBytes(content);
wr.ContentLength = data.Length;
wr.GetRequestStream().Write(data, 0, data.Length);

Upvotes: 1

Related Questions