Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

networking - C# auto detect proxy settings

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...