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

2019-04-14 08:21发布

问题:

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?

回答1:

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");


回答2:

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.



回答3:

You could easily use the ZipFile class like this:

using System.IO.Compression;

    class Program
    {
        static void Main()
        {
        // Create a ZIP file from the directory "source".
        // ... The "source" folder is in the same directory as this program.
        // ... Use optimal compression.
        ZipFile.CreateFromDirectory("source", "destination.zip",
            CompressionLevel.Optimal, false);

        // Extract the directory we just created.
        // ... Store the results in a new folder called "destination".
        // ... The new folder must not exist.
        ZipFile.ExtractToDirectory("destination.zip", "destination");
        }
    }

Please note that this is only available from .Net Framework version 4.5 onwards..



回答4:

I also had this problem, but I found a simple solution i want to Download this Zip File from "http://sodco.ir/Choobkhat/Update/update.zip" and extract them. but webClient not Download it.

My Solution:

Step 1: change my FileName from "D:\update.zip" to "D:\update.zi" webClient.DownloadFileAsync("http://sodco.ir/Choobkhat/Update/update.zip", "D:\\update.zi);

It will start downloading,After the download is completed:

Step 2: Rename update.zi to update.zip

File.Move("update.zi", "update.zip");

Step 3: extract them

ZipFile.ExtractToDirectory(Application.StartupPath + "\\update.zip", Application.StartupPath);

Refrence



回答5:

Full Example: Full sample at .Net Fiddle

public static bool DownloadFile(string filenameXML){
HttpWebRequest request;
HttpWebResponse response = null;
FileStream fs = null;
long startpoint = 0;
NewSourceFilePath=filenameXML;

fs = File.Create(NewSourceFilePath);
request = (HttpWebRequest)WebRequest.Create("http://---/file.zip");
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
request.Method = "GET";
request.ContentType = "gzip";
request.Timeout=10000;
request.Headers.Add("xRange", "bytes " + startpoint + "-");
response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
byte[] buffer = new byte[1024];
int read;
while ((read = streamResponse.Read(buffer, 0, buffer.Length)) > 0){
fs.Write(buffer, 0, read);}
fs.Flush();fs.Close();
}