Programmatically Set Browser Proxy Settings in C#

I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry:

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

Is going into the registry the best way to do this, or is there a more recommended approach? I'd like to avoid registry changes if there's an alternative solution.


Solution 1:

This depends somewhat on your exact needs. If you are writing a C# app and simply want to set the default proxy settings that your app will use, use the class System.Net.GlobalProxySelection (http://msdn.microsoft.com/en-us/library/system.net.globalproxyselection.aspx). You can also set the proxy for any particular connection with System.Net.WebProxy (http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx).

If you actually want to update the proxy settings in the registry, I believe that you'll need to use P/Invoke to call the WinAPI function WinHttpSetDefaultProxyConfiguration (http://msdn.microsoft.com/en-us/library/aa384113.aspx).

Solution 2:

from: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/19517edf-8348-438a-a3da-5fbe7a46b61a

Add these lines at the beginning of your code:

using System.Runtime.InteropServices; using Microsoft.Win32;

    [DllImport("wininet.dll")]
    public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
    public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
    public const int INTERNET_OPTION_REFRESH = 37;
    bool settingsReturn, refreshReturn;

And imply the code:

        RegKey.SetValue("ProxyServer", YOURPROXY);
        RegKey.SetValue("ProxyEnable", 1);

        // These lines implement the Interface in the beginning of program 
        // They cause the OS to refresh the settings, causing IP to realy update
        settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
        refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);