Harish's Blog on .Net

Wednesday, May 04, 2005

How to find out if proxy is enabled in the local computer


There are couple of ways we can retrieve the proxy settings in C# or VB.NET.

Method 1 : Read the settings directly from the registry.

When we change the proxy settings thorugh Internet Explorer, the settings is stored in the registry. We can read the registry values to check if the proxy is enabled and find the proxy server.

Microsoft.Win32.RegistryKey key =
Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\Microsoft\\Windows\\CurrentVersion\\Internet Settings");

string proxyEnabled = key.GetValue( "ProxyEnable" ).ToString();

The following code will return the proxy server address specified in the IE settings, even if it is not enabled.
string proxyServer = key.GetValue("ProxyServer") == null ?
string.Empty : key.GetValue("ProxyServer").ToString();


Method 2 : We can use the Webproxy class to get details about the current proxy settings.
System.Net.WebProxy webProxy = System.Net.WebProxy.GetDefaultProxy();

bool bypassProxyForLocal = webProxy.BypassProxyOnLocal;

Uri address = webProxy.Address;
if ( address != null )
{
string host = address.Host;
string port = address.Port.ToString();
}

Using the WebProxy class is a better solution. It exposes various properties using which we can retrieve information related to the proxy settings including port number, host address etc. Reading from registry directly returns a single string, which we may need to parse to extract the host address and port number.

0 Comments:

Post a Comment

<< Home