从CookieContainer中获取所有Cookie

/// <summary>
/// 把CookieContainer所有的Cookie读出来
/// </summary>
/// <param name="cc"></param>
/// <returns></returns>
private List <Cookie > GetAllCookies(CookieContainer cc)
{
    List<Cookie> lstCookies = new List< Cookie>();
    Hashtable table = ( Hashtable)cc.GetType().InvokeMember( "m_domainTable",
        System.Reflection. BindingFlags.NonPublic | System.Reflection.BindingFlags .GetField |
        System.Reflection. BindingFlags.Instance, null , cc, new object [] { });

    foreach (object pathList in table.Values)
    {
        SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list" ,
            System.Reflection. BindingFlags.NonPublic | System.Reflection.BindingFlags .GetField
            | System.Reflection. BindingFlags.Instance, null , pathList, new object[] { });
        foreach ( CookieCollection colCookies in lstCookieCol.Values)
            foreach ( Cookie c in colCookies)
                lstCookies.Add(c);
    }

    return lstCookies;
}


///////////////////////////////////////////////////以下是使用样例代码:
private string GetSkey()
{
    string skey = string.Empty;

    GetCookie();
    List<Cookie> listCookie = GetAllCookies(_cookie);
    foreach (Cookie c in listCookie)
    {
        if (c.Name == "skey")
        {
            skey = c.Value;
            break;
        }
    }
    return skey;
}
本文为“技术点滴”的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注