Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# auto detect proxy settings

C# 2008 SP1

I am using the code to detect if a proxy has been set under "Internet Options". If there is a proxy then I will set this in my webclient.

So I am just checking if the address of the proxy exists. If there is not, then there is no proxy to set in the webclient.

Is this the correct way to do this:

Many thanks for any advice,

WebProxy proxy = WebProxy.GetDefaultProxy();  if (proxy.Address.ToString() != string.Empty) {     Console.WriteLine("Proxy URL: " + proxy.Address.ToString());     wc.Proxy = proxy; } 

====== Code edit ======

[DllImport("wininet.dll", CharSet = CharSet.Auto)] private extern static bool InternetGetConnectedState(ref InternetConnectionState_e lpdwFlags, int dwReserved);  [Flags] enum InternetConnectionState_e : int {     INTERNET_CONNECTION_MODEM = 0x1,     INTERNET_CONNECTION_LAN = 0x2,     INTERNET_CONNECTION_PROXY = 0x4,     INTERNET_RAS_INSTALLED = 0x10,     INTERNET_CONNECTION_OFFLINE = 0x20,     INTERNET_CONNECTION_CONFIGURED = 0x40 }       // Return true or false if connecting through a proxy server public bool connectingThroughProxy() {     InternetConnectionState_e flags = 0;     InternetGetConnectedState(ref flags, 0);     bool hasProxy = false;      if ((flags & InternetConnectionState_e.INTERNET_CONNECTION_PROXY) != 0)     {         hasProxy = true;     }     else     {         hasProxy = false;     }      return hasProxy; } 
like image 980
ant2009 Avatar asked May 10 '09 01:05

ant2009


2 Answers

It appears that WebRequest.DefaultWebProxy is the official replacement for WebProxy.GetDefaultProxy.

You should be able to drop that in to your original code with only a little modification. Something like:

WebProxy proxy = (WebProxy) WebRequest.DefaultWebProxy; if (proxy.Address.AbsoluteUri != string.Empty) {     Console.WriteLine("Proxy URL: " + proxy.Address.AbsoluteUri);     wc.Proxy = proxy; } 
like image 62
Nathan Stohlmann Avatar answered Sep 28 '22 00:09

Nathan Stohlmann


First, GetDefaultProxy is marked as deprecated so you have no guarantee it will be around in even the immediate future. Second, Address can be null so the code you gave risks a NullReferenceException:

like image 41
Matthew Flaschen Avatar answered Sep 28 '22 01:09

Matthew Flaschen