Click here to Skip to main content
15,881,852 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.88/5 (4 votes)
25 Nov 2013CPOL 32.3K   1.2K   10  
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.

C#
//
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --