How can I get all Cookies of a CookieContainer?

前端 未结 4 1401
挽巷
挽巷 2020-11-30 09:41

I want to export a CookieContainer to JSON using Newtonsoft.Json but unfortunately CookieContainer hasn\'t an enumerator or stuff, so I can\'t cycle through it ...

<

4条回答
  •  野性不改
    2020-11-30 10:23

    This method will ensure to get all cookies, no matter what the protocol is:

    public static IEnumerable GetAllCookies(this CookieContainer c)
    {
        Hashtable k = (Hashtable)c.GetType().GetField("m_domainTable", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(c);
        foreach (DictionaryEntry element in k)
        {
            SortedList l = (SortedList)element.Value.GetType().GetField("m_list", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(element.Value);
            foreach (var e in l)
            {
                var cl = (CookieCollection)((DictionaryEntry)e).Value;
                foreach (Cookie fc in cl)
                {
                    yield return fc;
                }
            }
        }
    }
    

提交回复
热议问题