这是我从百度上搜到的:
[C#] 纯文本查看 复制代码
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int InternetSetCookieEx(string lpszURL, string lpszCookieName, string lpszCookieData, int dwFlags, IntPtr dwReserved);
public static string GetCookies(string url)
{
if (string.IsNullOrEmpty(url)) return null;
uint pcchCookieData = 256;
StringBuilder pchCookieData = new StringBuilder((int)pcchCookieData);
if (!InternetGetCookieEx(url, null, pchCookieData, ref pcchCookieData, 8192, IntPtr.Zero))
{
if (pcchCookieData < 0U)
return null;
pchCookieData = new StringBuilder((int)pcchCookieData);
if (!InternetGetCookieEx(url, null, pchCookieData, ref pcchCookieData, 8192, IntPtr.Zero))
return null;
}
string str = pchCookieData.ToString();
if (str.Contains("CNZZDATA"))
{
int length = str.IndexOf("CNZZDATA");
str = str.Substring(0, length);
}
return str;
}
这是咱们论坛的代码:
[C#] 纯文本查看 复制代码
//取当前webBrowser登录后的Cookie值
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static string GetCookieString(string url)
{
// Determine the size of the cookie
int datasize = 256;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
return null;
}
return cookieData.ToString();
}
我从百度上搜到的这个代码能正常获取cookie,论坛上的反而取不到。请问是什么原因呢? |