C# 从 URL 下载文件

7

你的URL指向一个HTML文件,这就是你得到的。你想下载哪个文件? - Tarik
如果您尝试在任何浏览器中打开该URL,将开始下载。 - C0deGen
5个回答

13

在 Fiddler 中查看请求,如果没有合法的 U/A 字符串,则请求将失败,因此:

WebClient wb = new WebClient();
wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe", "c:\\xxx\\xxx.exe");

我已经添加了上面的头文件,但对我没有起作用。我正在尝试下载一个加密文本和一个exe文件。 - Pabitra Dash

4
我相信这可以解决问题。
WebClient wb = new WebClient();
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe","file.exe");

1
如果您需要了解下载状态或使用凭据来发出请求,我建议使用以下解决方案:
WebClient client = new WebClient();
Uri ur = new Uri("http://remoteserver.do/images/img.jpg");
client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadDataCompleted += WebClientDownloadCompleted;
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");

以下是回调函数的实现:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

应该使用DownloadFileCompleted而不是DownloadDataCompleted。 - WTIFS

0
尝试使用WebClient.DownloadData 你将会得到一个byte[]类型的响应,然后你可以对它进行任何想要的操作。

0
有时服务器不允许您下载带有脚本/代码的文件。为了解决这个问题,您需要设置用户代理标头来欺骗服务器,使其认为请求来自浏览器。使用以下代码,它可以正常工作。已测试通过。
 var webClient=new WebClient();
 webClient.Headers["User-Agent"] =
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
 webClient.DownloadFile("the url","path to downloaded file");

这将按照您的期望工作,并且您可以下载文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接