如何使用C#从URL下载ZIP文件? [英] How can I download a ZIP file from a URL using C#?

查看:341
本文介绍了如何使用C#从URL下载ZIP文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我尝试了以下代码:

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.

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

知道发生了什么事吗?

推荐答案

这有效:

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

这篇关于如何使用C#从URL下载ZIP文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆