Search code examples
c#cookieswebbrowser-controlwebclientcookiecontainer

How to merge two CookieContainers so older cookies are overwritten?


Is there a standard method that does this, or do I have to get every cookie from the CookieContainer using reflection, manually check them, and then add them to a new CookieContainer?


Solution

  • You can add a Cookie or CookieCollection to another CookieCollection using CookieCollection.Add. If a cookie added has the same name as a pre-existing cookie in the collection the pre-existing cookie will be replaced with the new cookie.

    CookieCollection my_cookies = new CookieCollection();
    my_cookies.Add(new Cookie("id", "old_id_value"));
    CookieCollection new_cookies = new CookieCollection();
    new_cookies.Add(new Cookie("id", "new_id_value"));
    
    my_cookies.Add(new_cookies);
    
    foreach(Cookie c in my_cookies)
    {
        Console.WriteLine(c.Name + ": " + c.Value);
    }
    
    // prints "id: new_id_value"