How to get cookies info inside of a CookieContainer? (All Of Them, Not For A Specific Domain)

SilverLight picture SilverLight · Dec 3, 2012 · Viewed 42.8k times · Source

Please see the code below:

CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
int cookieCount = cookieJar.Count;

How can I get cookies info inside cookieJar? (All of them, not just for a specific domain.)
And how can I add or remove a cookie from that?

Answer

Parimal Raj picture Parimal Raj · Dec 28, 2012

reflection can be used to get the private field that holds all the domain key in CookieContainer object,

Q. How do i got the name of that private field ?

Ans. Using Reflector;

its is declared as :

private Hashtable m_domainTable;

once we get the private field, we will get the the domain key, then getting cookies is a simple iteration.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Net;
using System.Collections;

namespace ConsoleApplication4
{
    static class Program
    {
        private static void Main()
        {
            CookieContainer cookies = new CookieContainer();
            cookies.Add(new Cookie("name1", "value1", "/", "domain1.com"));
            cookies.Add(new Cookie("name2", "value2", "/", "domain2.com"));

            Hashtable table = (Hashtable)cookies.GetType().InvokeMember(
                "m_domainTable",                                                      
                BindingFlags.NonPublic |                                                                           
                BindingFlags.GetField |                                                                     
                BindingFlags.Instance,                                                                      
                null,                                                                            
                cookies,
                new object[]{}
            );

            foreach (var key in table.Keys)
            {
                Uri uri = new Uri(string.Format("http://{0}/", key));

                foreach (Cookie cookie in cookies.GetCookies(uri))
                {
                    Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}",
                        cookie.Name, cookie.Value, cookie.Domain);
                }
            }

            Console.Read();
        }
    }
}