C# – Use cookies from CookieContainer in WebBrowser

ccookiecontainernetwebbrowser-controlwinforms

Is there any way that I can actually use the cookies from a cookie container (taken from a WebRequest previously) and use them in a WebBrowser control? If so, how would I do this? This is for a Winforms application in C#.

Best Answer

You need to make use of InternetSetCookie. Here is a sample...

public partial class WebBrowserControl : Form
{
     private String url;

     [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
     public static extern bool InternetSetCookie(string lpszUrlName, string    lbszCookieName, string lpszCookieData);

     public WebBrowserControl(String path)
     {
          this.url = path;
          InitializeComponent();

          // set cookie
          InternetSetCookie(url, "JSESSIONID", Globals.ThisDocument.sessionID); 

          // navigate
          webBrowser.Navigate(url); 
     }
}