Search code examples
c#.netwebclienthttp-authentication

Using WebClient to ping a web site


I have a tiny app that I wanting to run and ping an internal web site. Here is the code:

using (var client = new WebClient())
{
    client.DownloadString("http://MyServer/dev/MyApp");
}

However, it is throwing the following error:

The remote server returned an error: (401) Unauthorized.

I have all the correct credentials to access the server. I am thinking I don't know how to use WebClient very well and I just need to set properties on the client object. Any ideas?


Solution

  • I found the answer. I needed to use the NetworkCredentials() method of WebClient. See below:

        using (var client = new WebClient())
        {
            client.Credentials = new NetworkCredential ("theUser", "thePassword", "theDomain"); 
            client.DownloadString("http://MyServer/dev/MyApp");
        }
    

    This is the URL that helped me