how to remove/update a cookie in cookie container c#?

confusedMind picture confusedMind · May 23, 2012 · Viewed 10.1k times · Source

I open a website using webbrowser control and then save cookies in cookieContainer , and later use HTTPwebrequest to process forward browsing pages etc.

The issue arises, when i make a search and it returns 100 pages,on the first page ,it saves a cookie named : ABC ,which i add to the cookiecontainer and move to the next page , on the second page again same Cookie named: ABC is given some value, but now i have two same cookies in cookiecontainer and when i move to the next page it does not work , as its taking the first cookie which messes everything.

How to solve this?

HttpWEBREQUEST FUNCTION:

 public string getHtmlCookies(string url)
    {
        string responseData = "";
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "*/*";
            request.AllowAutoRedirect = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Timeout = 30000;
            request.Method = "GET";
            request.CookieContainer = yummycookies;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                foreach (Cookie cookie in response.Cookies)
                {
                    string name = string.Empty;
                    name = cookie.Name;
                    string value = cookie.Value;
                    string path = "/";
                    string domain = "www.example.com";
                    yummycookies.Add(new Cookie(name.Trim(), value.Trim(), path, domain));

                }


                Stream responseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(responseStream);
                responseData = myStreamReader.ReadToEnd();
            }
            response.Close();


        }
        catch (Exception e)
        {
            responseData = "An error occurred: " + e.Message;
        }

        return responseData;

    }

Answer

RePierre picture RePierre · May 23, 2012

You can use SetCookies method.

var container = new System.Net.CookieContainer();
var uri = new Uri("http://www.example.com");
container.SetCookies(uri,"name=value");
container.SetCookies(uri,"name=value1");

Calling GetCookies(uri) will give a single cookie with Value=value1.

And in your case, the code would be something like

var uri = new Uri("http://www.example.com");
yummycookies.SetCookies(uri, response.Headers[HttpResponseHeader.SetCookie]);