1

I'm using the code provided by this answer to download and interact with websites.

https://stackoverflow.com/a/1031335/1689144

// establish the client and base
CookieAwareWebClient client = new CookieAwareWebClient();
client.BaseAddress = @"some_url";

// establish login data
var loginData = new NameValueCollection();
loginData.Add("username", Settings.Default.username.ToLower());
loginData.Add("password", Settings.Default.password);

// begin login
client.UploadValues("/login", "POST", loginData);

Here's where I have trouble. I thought CookieContainer to be a NameValueCollection. It isn't... How do I read the contents of CookieContainer?

//NOM NOM NOM cookies
var nomNomCookies = client.CookieContainer;
foreach (var cookie in nomNomCookies)
{
    //test
    Console.WriteLine(cookie.Name + " " + cookie.Value);
}
Community
  • 1
  • 1
Kyle
  • 5,407
  • 6
  • 32
  • 47

1 Answers1

1

If you want to use this hacky solution:

public static IEnumerable<Cookie> GetAllCookies(CookieContainer cookieContainer)
{
    var domainTable = (Hashtable)cookieContainer
                            .GetType()
                            .InvokeMember(
                                name: "m_domainTable",
                                invokeAttr: BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance,
                                binder: null,
                                target: cookieContainer,
                                args: new object[] { });

    return domainTable.Keys.Cast<string>()
                .Select(d => cookieContainer.GetCookies(new Uri("http://" + d.TrimStart('.'))))
                .SelectMany(c => c.Cast<Cookie>());

}
L.B
  • 114,136
  • 19
  • 178
  • 224