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

Man*_*lia 4 c# url webclient webclient-download

我想从某个网址下载 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!");
}
Run Code Online (Sandbox Code Playgroud)

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

知道发生了什么吗?

hus*_*ckr 5

这有效:

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");
Run Code Online (Sandbox Code Playgroud)