This CSharp (C#) code snippet shows how to request a web page using the HttpWebRequest class with basic authentication method enabled.

private string LoadHttpPageWithBasicAuthentication(string url, string username, string password)
    Uri myUri = new Uri(url);
    WebRequest myWebRequest = HttpWebRequest.Create(myUri);

    HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;

    NetworkCredential myNetworkCredential = new NetworkCredential(username, password);

    CredentialCache myCredentialCache = new CredentialCache();
    myCredentialCache.Add(myUri, "Basic", myNetworkCredential);

    myHttpWebRequest.PreAuthenticate = true;
    myHttpWebRequest.Credentials = myCredentialCache;

    WebResponse myWebResponse = myWebRequest.GetResponse();

    Stream responseStream = myWebResponse.GetResponseStream();

    StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);

    string pageContent = myStreamReader.ReadToEnd();



    return pageContent;
This website is making use of cookies for website analysis. Data is collected anonymously and solely for the purpose of improving the website. Do you agree to the use of cross-session cookies?