Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Passing Cookie Value from webbrowser Control to webclient in an Authenticated Environment

0.00/5 (No votes)
25 Nov 2013 1  
This tip will demonstrate how cookies are passed from one control to another control in C# .NET in authenticated webpage.

Introduction

This tip will demonstrate how cookies are passed from one control to another control in C# .NET in authenticated webpage. If we download the content of the webpage only in webclient method to save as popup window in webbrowser control, we pass the URL from webbrowser to webclient method and download the web content.

It downloads the files in web environment with authentication mode. We use two controls for downloading a file in authentication mode.

  1. Webbrowser: For navigating the webpage and passing the username and password and traversing the page from the file available area
  2. Webclient: We go for Webclient method to download the file in an authenticated environment because webbrowser control does not have the save method in background.

Using the Code

Browse the webpage in a webbrowser control and navigate the file area. Take the cookie of that page and pass the cookie values in an authenticated environment with webclient method.

//
Passing Cookie value from webbrowser to webclient:

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName,
StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

string cc = "";
uint datasize = 1024;

StringBuilder cookieData = new StringBuilder((int)datasize);
if (InternetGetCookieEx(dw_path, null, cookieData, ref datasize,
INTERNET_COOKIE_HTTPONLY, IntPtr.Zero) && cookieData.Length > 0)
{
   cc = cookieData.ToString();
}
else
{
cc = "";
}
wc.Headers.Add(HttpRequestHeader.Cookie , cc);
wc.DownloadFileAsync (new Uri(dw_path), f_down_path + "\\" + dw_fname);
while (wc.IsBusy)
{
Application.DoEvents();
}
wc.Dispose();
...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here