public class CookieHelper
{
[DllImport("Kernel32.dll")]
private extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int InternetSetCookieEx(string lpszURL, string lpszCookieName, string lpszCookieData, int dwFlags, IntPtr dwReserved);
public static string GetCookies(string url)
{
uint datasize = 256;
StringBuilder cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x40, IntPtr.Zero))
{
cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x40, IntPtr.Zero))
return null;
}
return cookieData.ToString();
}
public static int SetCookies(string url, string cookieName, string cookieData, DateTime expiresDate)
{
cookieData = string.Format("{0}={1};path=/;expires={2}"
, cookieName
, cookieData
, expiresDate.ToString("r"));
return InternetSetCookieEx(url, null, cookieData, 0x40, IntPtr.Zero);
}
/// <summary>
/// 获取错误提示
/// </summary>
/// <returns></returns>
public static string GetErrMsg()
{
var code = Marshal.GetLastWin32Error();
var tempptr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempptr, code, 0, ref msg, 255, ref tempptr);
return msg;
}
}
public class Program
{
const string domain = "http://yourdomain";
public static void Main()
{
try
{
SetCookie();
DisplayCookie();
}
catch (Exception e)
{
Console.WriteLine("
Error:{0}", e.Message);
}
finally
{
Console.WriteLine("
finished,any key to continue...");
Console.ReadKey();
}
}
private static void SetCookie()
{
var result = CookieHelper.SetCookies(domain, "TestCookie", "IAAAA", DateTime.Now.AddYears(-1));
Console.WriteLine(result);
Console.WriteLine(CookieHelper.GetErrMsg());
}
private static void DisplayCookie()
{
Console.WriteLine(CookieHelper.GetCookies(domain));
}
}