Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download a ZIP file from a URL using C#?

Tags:

c#

url

webclient

I want to download a ZIP file from some web URL. When I open the browser and write the URL, the browser directly start downloading the ZIP file. However what I want is to automate this using C# code.

I have tried the following code:

private void btnDownload_Click(object sender, EventArgs e) {
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
  webClient.DownloadFileAsync(new Uri("http://---/file.zip"), @"c:\file.zip");
}     

private void Completed(object sender, AsyncCompletedEventArgs e) {
  MessageBox.Show("Download completed!");
}

It seems that the download is working, but when I check the downloaded file I find it as 0 KB.

Any idea what's going on?

like image 533
Manoj Savalia Avatar asked Feb 06 '23 05:02

Manoj Savalia


2 Answers

This works:

WebClient webClient = new WebClient();
webClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
webClient.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
 webClient.DownloadFileAsync(new Uri("https://www.nseindia.com/content/historical/DERIVATIVES/2016/AUG/fo05AUG2016bhav.csv.zip"),"test1.zip");
like image 99
huse.ckr Avatar answered Feb 18 '23 22:02

huse.ckr


As I can see, your code corresponds to known antipattern Timer and Garbage Collector.

When btnDownload_Click is finished, the webClient variable becomes unreachable, and the garbage collector destroys it together with its functionality.

Try this:

private WebClient webClient = null;

private void btnDownload_Click(object sender, EventArgs e) {
  // Is file downloading yet?
  if (webClient != null)
    return;

  webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
  webClient.DownloadFileAsync(new Uri("http://---/file.zip"), @"c:\file.zip");
}     

private void Completed(object sender, AsyncCompletedEventArgs e) {
  webClient = null;
  MessageBox.Show("Download completed!");
}

Now `webClient is the member of the class and is reachable. Then the garbage collector will not destroy it.

like image 34
Mark Shevchenko Avatar answered Feb 18 '23 21:02

Mark Shevchenko