Pass cookie from Web Request to WebBrowser

Suppose you have some domain where you are navigating with a WebRequest object and you need to be able to browser that domain in a standard WebBrowser control, using the same cookies of the WebRequest.

The solution is really simple, you need to use the InternetSetCookieEx Windows API. First of all the import statement

1
2
3
4
5
6
7
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetSetCookieEx(
string url,
string cookieName,
StringBuilder cookieData,
Int32 dwFlags,
IntPtr lpReserved);

Now you can use in a simple helper function.

1
2
3
4
5
6
7
8
9
public static void SetCookieForBrowserControl(CookieContainer cc, Uri uri)
{
String hostName = uri.Scheme + Uri.SchemeDelimiter + uri.Host;
Uri hostUri = new Uri(hostName);
foreach (Cookie cookie in cc.GetCookies(hostUri))
{
InternetSetCookieEx(hostName, cookie.Name, new StringBuilder(cookie.Value), 0, IntPtr.Zero);
}
}

This technique is really useful if you perform a login with a standard WebRequest object, and then want to browse the site in a webbrowser control using the same login credentials you are using with the WebRequest object.

alk.