首先是获取webbrowser中cookie的方法(用webbrowser.Document.Cookie这个方法获取到的cookie不完整)
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref int pcchCookieData, int dwFlags, object lpReserved);
private 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存储到cookieContainer中
public void SetCookieContainer(string domain)
{
//清空已有的cookie
foreach (System.Net.Cookie cookie in cookieContainer1.GetCookies(new Uri(domain))) {
cookie.Expires = DateTime.Now.AddMinutes(-2);
}
string cookiestr = GetCookieString(domain);
if (cookieContainer1 == null)
{
cookieContainer1 = new System.Net.CookieContainer();
cookieContainer1.PerDomainCapacity = 53;//设置每个域名能存储的cookie数量。某些网站的cookie数量会大于默认值20
}
if (cookiestr != null)
{
foreach (string co in cookiestr.Split(';'))
{
cookieContainer1.SetCookies(new Uri(domain), co);
}
}
}