为什么在我的WebClient DownloadFileAsync方法下载空文件?

我有这个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) 

谢谢

更新:我更新了根本不存在空格的代码,但它仍然下载0个字节。

这是工作代码。 你有两件事没有做,这导致了0字节文件的下载。

  1. 你没有打电话给IsBusy 。 需要调用它以使代码等待当前线程完成,因为异步操作将在新线程上。
  2. 有问题的网站正在返回一个badgateway,除非您将请求视为来自常规Web浏览器。

创建一个空白控制台应用程序并将以下代码放入其中并进行试用。

将此代码粘贴到blank / new控制台应用程序的Program.cs文件中。

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

添加一个名为DownloadManager的新C#类文件,并将此代码放入其中。

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

现在构建并运行控制台应用程序。 您应该在控制台输出窗口中看到这样的进度。

完成后,您应该在targetdownloadedFile变量中指定的位置看到zip文件,在此示例中,该变量位于本地计算机上的C:\Temp\TestZip.zip

  objFeedBO = new FeedBO(); string strfilename = System.IO.Path.GetFileName(url); FileStream outputStream = new FileStream(DownloadPath + "\\" + strfilename, FileMode.Create); string targetdownloadedFile = @"D:\TestZip.php"; WebClient myWebClient = new WebClient(); myWebClient.DownloadFileAsync(new Uri(url), targetdownloadedFile); while (myWebClient.IsBusy) { }