title: Logging Into A Website Using C# Programmatically
body: <p>So, I've been scouring the web trying to learn more about how to log into websites programmatically using C#. I don't want to use a web client. I think I want to use something like HttpWebRequest and HttpWebResponse, but I have no idea how these classes work.</p>
  
  <p>I guess I'm looking for someone to explain how they work and the steps required to successfully log in to, say, WordPress, an email account, or any site that requires that you fill in a form with a username and password.</p>
  
  <p>Here's one of my attempts:</p>
  
  <pre><code>// Declare variables
          string url = textBoxGetSource.Text;
          string username = textBoxUsername.Text;
          string password = PasswordBoxPassword.Password;
  
          // Values for site login fields - username and password html ID's
          string loginUsernameID = textBoxUsernameID.Text;
          string loginPasswordID = textBoxPasswordID.Text;
          string loginSubmitID = textBoxSubmitID.Text;
  
          // Connection parameters
          string method = "POST";
          string contentType = @"application/x-www-form-urlencoded";
          string loginString = loginUsernameID + "=" + username + "&amp;" + loginPasswordID + "=" + password + "&amp;" + loginSubmitID;
          CookieContainer cookieJar = new CookieContainer();
          HttpWebRequest request;
  
          request = (HttpWebRequest)WebRequest.Create(url);
          request.CookieContainer = cookieJar;
          request.Method = method;
          request.ContentType = contentType;
          request.KeepAlive = true;
          using (Stream requestStream = request.GetRequestStream())
          using (StreamWriter writer = new StreamWriter(requestStream))
          {
              writer.Write(loginString, username, password);
          }
  
          using (var responseStream = request.GetResponse().GetResponseStream())
          using (var reader = new StreamReader(responseStream))
          {
              var result = reader.ReadToEnd();
              Console.WriteLine(result);
              richTextBoxSource.AppendText(result);
          }
  
          MessageBox.Show("Successfully logged in.");
  </code></pre>
  
  <p>I don't know if I'm on the right track or not. I end up being returned back to the login screen of whatever site I try. I've downloaded Fiddler and was able to glean a little bit of information about what information is sent to the server, but I feel completely lost. If anyone could shed some light here, I would greatly appreciate it.</p>