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; }
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; }
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With