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.
Webbrowser
: For navigating the webpage and passing the username and password and traversing the page from the file available area
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();
...