以编程方式通过Windows注册表设置代理地址,端口,用户,密码

时间:2010-08-05 18:01:19

标签: c# internet-explorer proxy

我正在编写一个小型C#应用程序,它将使用Internet Explorer与几个网站进行交互,并得到WatiN的帮助。

但是,它还需要不时使用代理。

我遇到Programmatically Set Browser Proxy Settings in C#,但这只能让我输入代理地址,我还需要输入代理用户名和密码。我怎么能这样做?

注意:

  • 解决方案是否会更改整个系统的Internet设置并不重要。但是,我更愿意只更改IE代理设置(对于任何连接)。
  • 该解决方案必须与IE8和Windows XP SP3或更高版本配合使用。
  • 我希望首先阅读代理设置,以便稍后我可以撤消我的更改。

修改

借助Microsoft.Win32.RegistryKey可访问的Windows注册表,我可以应用这样的代理:

RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", "127.0.0.1:8080");

但是如何指定用户名和密码才能登录代理服务器?

我还注意到,一旦更改了注册表,IE就不会刷新其连接的代理详细信息如何命令IE从注册表中刷新其连接设置?

由于

2 个答案:

答案 0 :(得分:2)

对于IE,您可以在注册表中使用相同的位置。只需设置ProxyServer =“user:password@127.0.0.1:8080”,但firefox完全拒绝此操作,并且不会尝试连接。

答案 1 :(得分:1)

以下是我通过代理访问Web服务时的方法:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);

        WebProxy proxy = new WebProxy(proxyUrl, port);

        NetworkCredential nwCred = new NetworkCredential(proxyUser, proxyPassword);

        CredentialCache credCache = new CredentialCache();
        credCache.Add(proxy.Address, "Basic", nwCred);
        credCache.Add(proxy.Address, "Digest", nwCred);
        credCache.Add(proxy.Address, "Negotiate", nwCred);
        credCache.Add(proxy.Address, "NTLM", nwCred);
        proxy.Credentials = credCache;

        proxy.BypassProxyOnLocal = false;

        request.Proxy = proxy;