HttpWebRequest Digest Authentication (C#/CSharp)

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

private string LoadHttpPageWithDigestAuthentication(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, "Digest", 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();

    responseStream.Close();

    myWebResponse.Close();

    return pageContent;
}