Detect proxy settings of default web browser

2019-04-07 20:57发布

问题:

MSDN sample

HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
WebProxy myProxy=new WebProxy();
// Obtain the 'Proxy' of the  Default browser.  
myProxy=(WebProxy)myWebRequest.Proxy;

Doesn't work. The error I get is: Unable to cast object of type 'WebProxyWrapper' to type 'System.Net.WebProxy'

What options do I have?

回答1:

HttpWebRequest.Proxy returns an IWebProxy interface, not WebProxy. Change that and it will work.

You can also use WebRequest.DefaultWebProxy or WebRequest.GetSystemWebProxy() to get the proxy details instead of making an HttpWebRequest and getting the proxy from that.



回答2:

To check automatically detect setting, use code:

RegistryKey registry = Registry.CurrentUser.OpenSubKey(
    "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 0);
RegistryKey registry2 = Registry.CurrentUser.OpenSubKey(
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections", true);
registry2.DeleteValue("DefaultConnectionSettings", false);
registry2.DeleteValue("SavedLegacySettings", false);


标签: c# proxy