C# 自动检测代理设置 [英] C# auto detect proxy settings

查看:43
本文介绍了C# 自动检测代理设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 2008 SP1

C# 2008 SP1

我正在使用代码来检测是否在Internet 选项"下设置了代理.如果有代理,那么我将在我的网络客户端中设置它.

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.

所以我只是检查代理的地址是否存在.如果没有,则在 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.

这是正确的做法吗:

非常感谢您的建议,

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

推荐答案

看来 WebRequest.DefaultWebProxy官方替代 WebProxy.GetDefaultProxy.

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

这篇关于C# 自动检测代理设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆