private static void RefreshProxySettings(string strProxy)
{
const int INTERNET_OPTION_PROXY = 38;
//const int INTERNET_OPEN_TYPE_PRECONFIG = 0; //IE setting
const int INTERNET_OPEN_TYPE_DIRECT = 1; //Direct
const int INTERNET_OPEN_TYPE_PROXY = 3; //Custom
INTERNET_PROXY_INFO ipi;
// Filling in structure
if (!string.IsNullOrEmpty(strProxy))
{
ipi.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
ipi.proxy = Marshal.StringToHGlobalAnsi(strProxy);
ipi.proxyBypass = Marshal.StringToHGlobalAnsi("local");
}
else if (strProxy == null)
{
//IE Default
var p = WebRequest.GetSystemWebProxy();
if (p.IsBypassed(new Uri("http://www.google.com/")))
{
ipi.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
ipi.proxy = IntPtr.Zero;
ipi.proxyBypass = IntPtr.Zero;
}
else
{
ipi.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
ipi.proxy = Marshal.StringToHGlobalAnsi(p.GetProxy(new Uri("http://www.google.com/")).Authority);
ipi.proxyBypass = Marshal.StringToHGlobalAnsi("local");
}
}
else
{
ipi.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
ipi.proxy = IntPtr.Zero;
ipi.proxyBypass = IntPtr.Zero;
}
try
{
// Allocating memory
var pIpi = Marshal.AllocCoTaskMem(Marshal.SizeOf(ipi));
if (pIpi.Equals(IntPtr.Zero)) return;
try
{
// Converting structure to IntPtr
Marshal.StructureToPtr(ipi, pIpi, true);
var ret = InternetSetOption(IntPtr.Zero,
INTERNET_OPTION_PROXY,
pIpi,
Marshal.SizeOf(ipi));
}
finally
{
Marshal.FreeCoTaskMem(pIpi);
}
}
finally
{
ipi.Dispose();
}
}