P/Invoke 宣告
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string url, string name, string data);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetGetCookie(string url, string name, StringBuilder data, ref int size);
完整流程:讀取既有 Cookie → 刪除舊檔 → 重寫並設定遠期 Expires
// 1. 取得現有 Cookie
var cookie = new StringBuilder(2048);
int size = cookie.Length;
InternetGetCookie("https://www.example.com", null, cookie, ref size);
// 2. 刪除本地 Cookie 檔案 (可選,視需求)
foreach (var file in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies))) {
if (file.ToLower().Contains("example")) File.Delete(file);
}
// 3. 重寫並加上 Expires=2099 年
foreach (var pair in cookie.ToString().Split(';')) {
var kv = pair.Split('=');
string name = kv[0].Trim();
string value = kv[1].Trim() + ";expires=Sun, 22-Feb-2099 00:00:00 GMT";
InternetSetCookie("https://www.example.com", name, value);
// 若有多子域名,逐一設定
InternetSetCookie("https://forum.example.com", name, value);
}
適用場景
- 自動化測試需長期保持登入狀態。
- 爬蟲/整合工具模擬持久會話。
- **注意**:直接操作 IE Cookie 存儲,僅影響 IE/Edge (舊版) 與使用 wininet 的應用,不影響 Chrome/Firefox。