Search code examples
c#stringconverterscookiecontainer

How convert CookieContainer to string?


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",


Solution

  • 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.