如何使用 C# 从 URL 下载 ZIP 文件?

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

我想从某个网站下载 ZIP 文件 URL。 当我打开浏览器并写入 URL 时,浏览器直接开始下载 ZIP 文件。但是我想要的是使用 C# 代码自动执行此操作。

我试过以下代码:

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

似乎下载正常,但是当我检查下载的文件时,我发现它是 0 KB。

知道发生了什么事吗?

完整示例: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();
}

如我所见,您的代码对应于已知的反模式 Timer and Garbage Collector

btnDownload_Click 完成时,webClient 变量变得不可访问,垃圾收集器将其连同其功能一起销毁。

试试这个:

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

现在 `webClient 是 class 的成员并且可以访问。那么垃圾收集器就不会销毁它了。

这个有效:

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

您可以像这样轻松使用 ZipFile class:

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

请注意,这只是 available from .Net Framework version 4.5 之后..

我也遇到了这个问题,不过我找到了一个简单的解决方法 我想从“http://sodco.ir/Choobkhat/Update/update.zip”下载这个 Zip 文件 并提取它们。但是 webClient 不下载它。

我的解决方案:

第 1 步: 将我的文件名从 "D:\update.zip" 更改为 "D:\update.zi" webClient.DownloadFileAsync("http://sodco.ir/Choobkhat/Update/update.zip", "D:\update.zi);

会开始下载,下载完成后:

步骤 2: 将 update.zi 重命名为 update.zip

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

第 3 步: 提取它们

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

Refrence