Connect .Net project to a website

Nicholas Nguyen 21 Reputation points
2022-04-12T00:16:28.663+00:00

Hi everyone,

I want to login to a website (any website with a login screen) but instead of typing my credentials into a website's login text fields, I want my C# code to do it for me automatically.

The issue is that I don't know how to connect my .Net project to interactive with an external website. I tried using a webBrowser control but it's not efficient.

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Jack J Jun 25,316 Reputation points
    2022-04-12T06:44:40.32+00:00

    @Nicholas Nguyen , based on your description, you could try the following code to login into a website in the winform:

    private void Form1_Load(object sender, EventArgs e)  
            {  
                webBrowser1.Navigate("https://somesite.com/");  
            }  
      
            private void button1_Click(object sender, EventArgs e)  
            {  
                if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)  
                {  
                    HtmlDocument htmlDoc = this.webBrowser1.Document;  
                    ////set account  
                    HtmlElement id = htmlDoc.GetElementById("username");  
                    id.SetAttribute("value", txtName.Text.Trim());  
                    //set password  
                    HtmlElement pwd = htmlDoc.GetElementById("password");  
                    pwd.SetAttribute("value", txtPassword.Text.Trim());  
                    //login  
                    var btn = htmlDoc.GetElementsByTagName("div").Cast<HtmlElement>().Where(i=>i.InnerText== "sign in ").First();  
                    if (btn != null)  
                    {  
                        btn.InvokeMember("click");  
                    }  
                }  
      
            }  
    

    Note: We need to achieve the htmlelement for username, password and sign in button and set the value for username and password and finally click the button.

    Example html:

    192070-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.