C# code for accessing the network through a proxy server

How to setup proxy authentication and details

ICredentials credentials = CredentialCache.DefaultCredentials;
IWebProxy proxy = new WebProxy(proxyServerHost, proxyServerPort);
proxy.Credentials = credentials;

The code (above) creates a set of credentials, in this case we get the user’s DefaultCredentials and ultimately places the credentials into the IWebProxy.

The IWebProxy is then instantiated with the host name and the port of the proxy server.

Let’s use the proxy

Now to use the web proxy obviously requires the library/framework to support proxies. So this is just one example using the .NET WebClient class.

using (WebClient wc = new WebClient())
{
   if(proxy != null)
   {
      wc.Proxy = proxy;
   }
   byte[] data = wc.DownloadData(url);
}