Use Application.GetCookie to add cookie to cookieContainer

c# cookies html-agility-pack webbrowser-control wpf

Question

Using WPF I need to make a call with HtmlAgilityPack.HtmlWeb that needs a cookie from my Application.

I tried the following code but I'm getting an error:

HtmlWeb web = new HtmlWeb();
web.PreRequest += request =>
{
   CookieContainer cookieContainer = new CookieContainer();
   cookieContainer.Add(new Cookie("name",Application.GetCookie(uri)){Domain = uri.Host});
   request.CookieContainer = cookieContainer;
    return true;
};

I'm getting the following error: An exception of type 'System.Net.CookieException' occurred in System.dll but was not handled in user code

Additional information: The 'Value'='visit="v=1&M"... lang=v=2&lang=en-us' part of the cookie is invalid.

Accepted Answer

Here's what solved my error:

web.PreRequest += request =>
{
    CookieContainer cookieContainer = new CookieContainer();
    string str = Application.GetCookie(uri);
    foreach (string s in str.Split(';'))
    {
        int charIndex = s.IndexOf('=');
        string a = s.Substring(0, charIndex).Trim();
        string b = s.Substring(charIndex+1, s.Length - charIndex-1);
        cookieContainer.Add(new Cookie(a,b) { Domain = uri.Host });
    }
    request.CookieContainer = cookieContainer;
    return true;
};



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why