最近在做一个通过HttpWebRequest来实现登陆和自动发信息的小软件虽然还没有实现但是今天从一个老外的网站上看到了一个获取CookieContainer很好的方法拿出来共享一下这是我看到过代码最少而且很不错的了 using System; using SystemRuntimeInteropServices; using SystemText; using SystemNet; namespace NExplusNSiter { /**//// <summary> /// 获取Cookie的方法类 /// </summary> public class CookieManger { /**//// <summary> /// 通过COM来获取Cookie数据 /// </summary> /// <param name=url>当前网址</param> /// <param name=cookieName>CookieName</param> /// <param name=cookieData>用于保存Cookie Data的<see cref=StringBuilder/>实例</param> /// <param name=size>Cookie大小</param> /// <returns>如果成功则返回<c>true</c>否则返回<c>false</c></returns> [DllImport(wininetdll SetLastError = true)] public static extern bool InternetGetCookie( string url string cookieName StringBuilder cookieData ref int size); /**//// <summary> /// 获取当前<see cref=Uri/>的<see cref=CookieContainer/>实例 /// </summary> /// <param name=uri>当前<see cref=Uri/>地址</param> /// <returns>当前<see cref=Uri/>的<see cref=CookieContainer/>实例</returns> public static CookieContainer GetUriCookieContainer(Uri uri) { CookieContainer cookies = null; // 定义Cookie数据的大小 int datasize = ; StringBuilder cookieData = new StringBuilder(datasize); if (!InternetGetCookie(uriToString() null cookieData ref datasize)) { if (datasize < ) return null; // 确信有足够大的空间来容纳Cookie数据 cookieData = new StringBuilder(datasize); if (!InternetGetCookie(uriToString() null cookieData ref datasize)) return null; } if (cookieDataLength > ) { cookies = new CookieContainer(); cookiesSetCookies(uri cookieDataToString()Replace(; )); } return cookies; } } } 是不是相当简单阿希望对大家有一点用处 l |