James Teare
James Teare

Reputation: 372

Downloading a file from a URL using a cookie

I am attempting to download a file from a web server e.g.

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

Upvotes: 1

Views: 3062

Answers (2)

nunespascal
nunespascal

Reputation: 17724

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;
    }
}

Upvotes: 4

Sandeep Singh Rawat
Sandeep Singh Rawat

Reputation: 1647

Make a HTTP get request to the page containg cookie, store the cookie and attach to second request to getfile.

ToDo: Add a sample

Upvotes: 1

Related Questions