tags:

views:

286

answers:

1

I'm trying to get a html source of a website through C# code. When I access the site with windows authentication the following code works:

using (WebClient client = new WebClient())
            {
                client.Credentials = CredentialCache.DefaultCredentials;
                using (Stream stream = client.OpenRead("http://intranet/"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    MessageBox.Show(reader.ReadToEnd());
                }
            }

when I enter my domain credentials manually i get an "unauthenticated" message:

using (WebClient client = new WebClient())
            {
                NetworkCredential credentials = new NetworkCredential("username", "pass", "domain");
                client.Credentials = credentials;
                using (Stream stream = client.OpenRead("http://intranet/"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    MessageBox.Show(reader.ReadToEnd());
                }
            }

Why is it so?

A: 

Try this:

CredentialCache cc = new CredentialCache();
cc.Add(
    new Uri("http://intranet/"), 
    "NTLM", 
    new NetworkCredential("username", "pass", "domain"));
client.Credentials = cc;
Darin Dimitrov
works, thanks, any explanation?
agnieszka
You need to specify the authentication type. When the server challenges the client with NTLM authentication the ICredentials.GetCredential method will be called on WebClient.Credentials with `authType = "NTLM"`. If you used `WebClient.Credential = new NetworkCredential(...)` as no authentication type is specified the client won't be able to respond correctly. `CredentialCache` already implements this functionality.
Darin Dimitrov