RAHUL
RAHUL

Reputation: 127

Downloading a file from a website using C#

I am trying to download a file from a website using the following code:

WebClient webClient = new WebClient();
webClient.DownloadFile("http://www.nseindia.com/content/historical/EQUITIES/2011/MAR/cm07MAR2011bhav.csv.zip", @"c:\myfile.txt");

The exception shown is "forbidden error 403"

It means page not found but I can download that file using java code and also I can directly download it from that website.

How do I download this using C# code?

Upvotes: 8

Views: 9809

Answers (5)

Raz
Raz

Reputation: 1

using (WebClient wc = new WebClient())
{
  wc.Headers.Add("Referer:https://www.nseindia.com/products/content/equities/equities/archieve_eq.htm");
  wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
  wc.DownloadFile(url, fileName);
}

Upvotes: 0

Ritch Melton
Ritch Melton

Reputation: 11608

The first thing to notice is that if you try the URL in your browser, the file does download. What that tells you is that you need to configure the WebClient to send headers mimicking what the website would expect a browser to do. This is what works for me:

        var wc = new WebClient();
        var ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
        wc.Headers.Add(HttpRequestHeader.UserAgent, ua);
        wc.Headers["Accept"] = "/";
        wc.DownloadFile("http://www.nseindia.com/content/historical/EQUITIES/2011/MAR/cm07MAR2011bhav.csv.zip", @"d:\myfile.txt");

As an aside, saving to the C: root is problematic. Save somewhere else.

Upvotes: 6

BernzSed
BernzSed

Reputation: 1139

I tested that URL with wget, and got a 403 error. I was able to solve that problem by adding a user-agent string to the header

Try adding a user-agent string to the header, using webClient.Headers.Add(HttpRequestHeader.UserAgent, "blah")

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 160992

You need to set the following two headers for this to work:

  • User-Agent: set to just some standard browser user-agent
  • Accept: set to accept "application/zip"

Example (tested):

WebClient webClient = new WebClient();
webClient.Headers.Add("Accept", "application/zip");
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
webClient.DownloadFile("http://www.nseindia.com/content/historical/EQUITIES/2011/MAR/cm07MAR2011bhav.csv.zip", @"D:\test\test.zip");

Upvotes: 2

Raj
Raj

Reputation: 1770

Try something like

WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;

Upvotes: -2

Related Questions