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

hea*_*ude 7 c# url download

我有这个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字节文件的下载.

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

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

将此代码粘贴到空白/新控制台应用程序的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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

添加一个名为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!!!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在构建并运行控制台应用程序.您应该在控制台输出窗口中看到进度,如此.

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