C#一個到多個Cookie的字串添加到CookieCollection集合中【isGood代碼】
來源:互聯網
上載者:User
C#一個到多個Cookie的字串添加到CookieCollection集合中多個網站(Domain)與多個路徑(Path)與多個Cookie名(c.name)的字元要添加到CookieCollection集合中在網上找不到可行的方法,isGood用一天寫出的添加到CookieCollection集合中多用代碼:/// <summary>/// 一個到多個Cookie的字串添加到CookieCollection集合中【isGood代碼】/// </summary>/// <param name="s">Cookie的字串</param>/// <param name="defaultDomain">網站主機部分</param>public static CookieCollection strCokAddCol(string s, string defaultDomain){ CookieCollection cc = new CookieCollection(); if (string.IsNullOrEmpty(s) || s.Length < 5 || s.IndexOf("=") < 0) return cc; if (string.IsNullOrEmpty(defaultDomain) || defaultDomain.Length < 5) return cc; s.TrimEnd(new char[] { ';'}).Trim(); Uri urI = new Uri(defaultDomain); defaultDomain = urI.Host.ToString(); //用軟體截取的cookie會帶有expires,要把它替換掉【isGood代碼】if (s.IndexOf("expires=") >= 0){ s = replace(s, @"expires=[\w\s,-:]*GMT[;]?", "");} //只有一個cookie直接添加【isGood代碼】if (s.IndexOf(";") < 0){ System.Net.Cookie c = new System.Net.Cookie(s.Substring(0, s.IndexOf("=")), s.Substring(s.IndexOf("=") + 1)); c.Domain = defaultDomain; cc.Add(c); return cc;} //不同網站與不同路徑一般是以英文道號分別【isGood代碼】 if (s.IndexOf(",") > 0) { s.TrimEnd(new char[] { ',' }).Trim(); foreach (string s2 in s.Split(',')) { cc = strCokAddCol(s2, defaultDomain, cc); } return cc; } else //同網站與同路徑,不同.Name與.Value【isGood代碼】 { return strCokAddCol(s, defaultDomain, cc); }}//添加到CookieCollection集合部分private static CookieCollection strCokAddCol(string s, string defaultDomain, CookieCollection cc){ try { s.TrimEnd(new char[] { ';' }).Trim(); System.Collections.Hashtable hs = new System.Collections.Hashtable(); foreach (string s2 in s.Split(';')) { string s3 = s2.Trim(); if (s3.IndexOf("=") > 0) { string[] s4 = s3.Split('='); hs.Add(s4[0].Trim(), s4[1].Trim()); } } string defaultPath = "/"; foreach (object Key in hs.Keys) { if (Key.ToString().ToLower() == "path") { defaultPath = hs[Key].ToString(); } else if (Key.ToString().ToLower() == "domain") { defaultDomain = hs[Key].ToString(); } }//【isGood代碼】 foreach (object Key in hs.Keys) { if (!string.IsNullOrEmpty(Key.ToString()) && !string.IsNullOrEmpty(hs[Key].ToString())) { if (Key.ToString().ToLower() != "path" && Key.ToString().ToLower() != "domain") { Cookie c = new Cookie(); c.Name = Key.ToString(); c.Value = hs[Key].ToString(); c.Path = defaultPath; c.Domain = defaultDomain; cc.Add(c); } } } } catch {} return cc;} 替換字元 /// <summary>/// 替換字元【isGood代碼】/// </summary>/// <param name="strSource">來源</param>/// <param name="strRegex">運算式</param>/// <param name="strReplace">取代</param>public static string replace(string strSource, string strRegex, string strReplace){ try { Regex r; r = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline); string s = r.Replace(strSource, strReplace); return s; } catch { return strSource; }} 【isGood代碼】心中時常裝有一盤人生的大棋,天作棋盤,星作棋子,在鬥轉星移中,只有不斷地搏擊人生,人生才有意義,生命才能彰顯光輝,才能收穫一分永恒。