C#自动检测代理设置

C#2008 SP1

我正在使用代码来检测是否已在“Internet选项”下设置了代理。 如果有代理,那么我将在我的webclient中设置它。

所以我只是检查代理的地址是否存在。 如果没有,那么webclient中没有设置代理。

这是正确的方法:

非常感谢任何建议,

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

======代码编辑======

 [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; } 

似乎WebRequest.DefaultWebProxy是WebProxy.GetDefaultProxy的官方替代品 。

只需稍加修改,您就可以将其放入原始代码中。 就像是:

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

WebClient等使用WinHTTP设置(不是IE设置),所以最简单的方法是配置WinHTTP! 在XP等上你可以使用:

 proxycfg -u 

将当前IE设置导入WinHTTP存储。 之后, WebClient等应该能够使用相同的设置而不会出现问题。 在Vista和Windows 7上,现在可以在以下位置找到:

 netsh winhttp import proxy ie 

您需要以管理员身份运行它。

首先, GetDefaultProxy被标记为已弃用,因此您无法保证即使在不久的将来它也会出现。 其次, Address可以为null,因此您提供的代码存在NullReferenceException风险:

请尝试以下方法:

 public string GetMeMyInfo(string searchCriteria) { // Instatiate the web service and declare the necessary variables WsService.WsServiceBus oWsGetInfo = new WsService.WsServiceBus(); // Configure the Web Service Proxy oWsGetInfo.Proxy = System.Net.WebProxy.GetDefaultProxy(); oWsGetInfo.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; // Invoke the web service return oWsGetInfo.GetInfo4Me(searchCriteria); } 

例如,在调用您的Web服务之前,这将获得默认代理设置和凭据。

查看System.Net.Configuration.ProxyElement类。 这可能包含您正在寻找的信息。

你描述的是什么工作,你也可以在注册表中查看。

这是我写的用于检查代理的powershell脚本:

 function get-proxy { $path = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" $reg = get-itemproperty $path return $reg } 

将我的请求代理设置为WebRequest.GetSystemWebProxy()解决了这个问题。

WebProxy.GetDefaultProxy()是实际的方式,但现在已弃用。

       

在application.config文件中使用此代码段。

这对我有用

  var proxy = WebRequest.GetSystemWebProxy(); Uri testUrl = new Uri("http://proxy.example.com"); proxyUrl = proxy.GetProxy(testUrl); if (proxyUrl != testUrl) //Use your proxy here else //We are not using a proxy