我在使用 wininet 设置代理用户名和密码时遇到问题。
下面的代码设置了代理,但用户名和密码失败,错误代码为“12018”
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
private void RefreshIESettings(string strProxy,string proxyUsername,string proxyPassword) {
const int INTERNET_OPTION_PROXY = 38;
const int INTERNET_OPEN_TYPE_PROXY = 3;
const int INTERNET_OPTION_PROXY_USERNAME = 43;
const int INTERNET_OPTION_PROXY_PASSWORD = 44;
IntPtr username = Marshal.StringToHGlobalAnsi(proxyUsername);
IntPtr password = Marshal.StringToHGlobalAnsi(proxyPassword);
INTERNET_PROXY_INFO struct_IPI;
struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");
IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));
Marshal.StructureToPtr(struct_IPI, intptrStruct, true);
bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));
Marshal.GetNativeVariantForObject(proxyUsername, username);
Marshal.GetNativeVariantForObject(proxyPassword, password);
bool resultF = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_USERNAME, username, proxyUsername.Length);
var errorF = Marshal.GetLastWin32Error();
//-- Set Proxy Password
bool resultG = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_PASSWORD, password, proxyPassword.Length + 1);
var errorG = Marshal.GetLastWin32Error();