我有这个C#代码,但最终的esi.zip结果是0长度或基本上是空的.URL确实存在并确认手动下载文件.我很困惑买这个.
string zipPath = @"C:\download\esi.zip";
Client.DownloadFileAsync(new Uri("http://ec.europa.eu/economy_finance/db_indicators
/surveys/documents/series/nace2_ecfin_1409/all_surveys_total_sa_nace2.zip"), zipPath)
Run Code Online (Sandbox Code Playgroud)
谢谢
更新:我更新了根本不存在空格的代码,但它仍然下载0个字节.
Shi*_*iva 12
这是工作代码.你有两件事没有做,这导致了0
字节文件的下载.
IsBusy
.需要调用它以使代码等待当前线程完成,因为异步操作将在新线程上.创建一个空白的控制台应用程序并将以下代码放入其中并尝试一下.
namespace TestDownload
{
class Program
{
static void Main(string[] args)
{
string sourceUrl = "http://ec.europa.eu/economy_finance/db_indicators/surveys/documents/series/nace2_ecfin_1409/all_surveys_total_sa_nace2.zip";
string targetdownloadedFile = @"C:\Temp\TestZip.zip";
DownloadManager downloadManager = new DownloadManager();
downloadManager.DownloadFile(sourceUrl, targetdownloadedFile);
}
}
}
Run Code Online (Sandbox Code Playgroud)
using System;
using System.ComponentModel;
using System.Net;
namespace TestDownload
{
public class DownloadManager
{
public void DownloadFile(string sourceUrl, string targetFolder)
{
WebClient downloader = new WebClient();
// fake as if you are a browser making the request.
downloader.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged +=
new DownloadProgressChangedEventHandler(Downloader_DownloadProgressChanged);
downloader.DownloadFileAsync(new Uri(sourceUrl), targetFolder);
// wait for the current thread to complete, since the an async action will be on a new thread.
while (downloader.IsBusy) { }
}
private void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// print progress of download.
Console.WriteLine(e.BytesReceived + " " + e.ProgressPercentage);
}
private void Downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
// display completion status.
if (e.Error != null)
Console.WriteLine(e.Error.Message);
else
Console.WriteLine("Download Completed!!!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
当它完成时,您应该在targetdownloadedFile
变量中指定的位置看到zip文件,在本示例中,该文件位于C:\Temp\TestZip.zip
本地计算机上.