Alex Rivera | Logout

C# auto detect proxy settings

Asked 2009-05-10T01:00:53.157
28

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

2 Answers

3

Try the following:

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

That will get the default proxy setting and credentials before invoking your web service for example.

answered 2012-06-15T13:41:15.327
2

Setting my request proxy to WebRequest.GetSystemWebProxy() solved the problem.

WebProxy.GetDefaultProxy() is the actual way but it is now deprecated.

answered 2013-01-28T21:09:35.400

Your Answer