I am attempting to download a file from a web server eg
http://web.server.com/getfile=2
Now in the web browser I can do this, since I have authenticated myself and can view the cookie allowing to access the file.
I have done a fair bit of research and believe a cookie container would hold the cookie, although I am unable to determine how then you can download this file from within C# using the CookieContainer
In c# you should use a WebClient. Although it can be used independently, code like this will reduce your headache of adding a cookie header everytime.
public class CookieAwareWebClient : WebClient
{
private readonly CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = m_container;
}
return request;
}
}
Make a HTTP get request to the page containg cookie, store the cookie and attach to second request to getfile.
ToDo: Add a sample
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.