How convert CookieContainer to string?

user1088259 picture user1088259 · Jul 21, 2016 · Viewed 6.9k times · Source

I try loop cookie container with loop, but its return error. How correct convert CookieContainer to string

foreach (Cookie item in cookieContainer)
{
    var data = item.Value + "=" + item.Name;
}

Error 2 The foreach statement can not be used for variables of type "System.Net.CookieContainer",

Answer

Ben Fogel picture Ben Fogel · Jul 21, 2016

If you are only interested in the cookies for a specific domain, then you can iterate using the GetCookies() method.

var cookieContainer = new CookieContainer();
var testCookie = new Cookie("test", "testValue");
var uri = new Uri("https://www.google.com");
cookieContainer.Add(uri, testCookie);

foreach (var cookie in cookieContainer.GetCookies(uri))
{
    Console.WriteLine(cookie.ToString()); // test=testValue
}

If your interested in getting all the cookies, then you may need to use reflection as provided by this answer.