3

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

CMedina
  • 4,034
  • 3
  • 24
  • 39
user1088259
  • 345
  • 13
  • 34

2 Answers2

4

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.

Community
  • 1
  • 1
Ben Fogel
  • 541
  • 5
  • 13
0

Sample :

public static void Main(string[] args)
    {   
        if (args == null || args.Length != 1)
        {
            Console.WriteLine("Specify the URL to receive the request.");
            Environment.Exit(1);
        }
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
        request.CookieContainer = new CookieContainer();

        HttpWebResponse response = (HttpWebResponse) request.GetResponse();



        // Print the properties of each cookie.
        foreach (Cookie cook in response.Cookies)
        {                    
            // Show the string representation of the cookie.
            Console.WriteLine ("String: {0}", cook.ToString());
        }
    }
Thennarasan
  • 698
  • 6
  • 11