how to add proxy authentication details to webclient object

Kumar picture Kumar · Jun 27, 2012 · Viewed 10.4k times · Source

I have some code that's throwing a 407 unauthorized exception.

I am trying to download a file and below is my example code. I've tried with netcredentials and webproxy but in vain.

WebClient webClient = new WebClient();
NetworkCredential netCred=new NetworkCredential();
netCred.UserName="<<userid>>";
netCred.Password="<<password>>";
netCred.Domain="<<windowsdomainname>>";
webClient.Credentials = netCred;
WebProxy wp = new WebProxy();
wp.Credentials = netCred;
wp.Address = new Uri(@"http://proxy-xx.xxxx.co.uk:8080/proxy.pac");
webClient.Proxy = wp;
webClient.DownloadFile("http://www.win-rar.com/postdownload.html?&L=0", @"c:\winrar.exe");

Answer

Robert Kerr picture Robert Kerr · Jan 28, 2014

I was getting 407 before finding your question. Modified your source to the following, which works for me:

try
{
    var netCred = new NetworkCredential { UserName = "ununun", Password = @"pwpwpw", Domain = @"domain" };
    var webProxy = new WebProxy { Credentials = netCred };
    var webClient = new WebClient { Proxy = webProxy };
    webClient.DownloadFile(url, saveFileName);
}
catch (Exception ex)
{
    Console.WriteLine("Exception:\n{0}\n{1}", ex.Message, ex.StackTrace);
    return;
}