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

本文关键字:下载 ZIP 文件 URL 何使用 | 更新日期: 2023-09-27 18:05:15

我想从某个web URL下载一个ZIP文件。当我打开浏览器并写入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!");
}

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

知道发生了什么事吗?

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

这是有效的:

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

正如我所看到的,您的代码对应于已知的反模式定时器和垃圾回收器。

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是类的成员,并且是可访问的。然后垃圾收集器不会销毁它。

您可以很容易地使用ZipFile类,如下所示:

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

请注意,这仅适用于.Net Framework 4.5版以后的版本。。

我也遇到了这个问题,但我找到了一个简单的解决方案我想从"http://sodco.ir/Choobkhat/Update/update.zip"并提取它们。但是webClient没有下载。

我的解决方案:

步骤1:将我的FileName从"D:''update.zip"更改为"D:''uupdate.zip"webClient.DownloadFileAsync("http://sodco.ir/Choobkhat/Update/update.zip", "D:''update.zi);

它将开始下载,下载完成后:

第2步:将update.zip重命名为update.zipp

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

第3步:提取

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

折射率

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