How can I get all Cookies of a CookieContainer?

前端 未结 4 1398
挽巷
挽巷 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:15

    A solution using reflection:

    public static CookieCollection GetAllCookies(CookieContainer cookieJar)
    {
        CookieCollection cookieCollection = new CookieCollection();
    
        Hashtable table = (Hashtable) cookieJar.GetType().InvokeMember("m_domainTable",
                                                                        BindingFlags.NonPublic |
                                                                        BindingFlags.GetField |
                                                                        BindingFlags.Instance,
                                                                        null,
                                                                        cookieJar,
                                                                        new object[] {});
    
        foreach (var tableKey in table.Keys)
        {
            String str_tableKey = (string) tableKey;
    
            if (str_tableKey[0] == '.')
            {
                str_tableKey = str_tableKey.Substring(1);
            }
    
            SortedList list = (SortedList) table[tableKey].GetType().InvokeMember("m_list",
                                                                        BindingFlags.NonPublic |
                                                                        BindingFlags.GetField |
                                                                        BindingFlags.Instance,
                                                                        null,
                                                                        table[tableKey],
                                                                        new object[] { });
    
            foreach (var listKey in list.Keys)
            {
                String url = "https://" + str_tableKey + (string) listKey;
                cookieCollection.Add(cookieJar.GetCookies(new Uri(url)));
            }
        }
    
        return cookieCollection;
    }
    

提交回复
热议问题