DownloadFileAsync不下载文件

时间:2014-07-17 11:14:48

标签: c#

我正在尝试编写从网上下载一个文件的简单应用。

class Program
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri("http://download.thinkbroadband.com/100MB.zip");

        // Specify that the DownloadFileCallback method gets called
        // when the download completes.
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback2);
        // Specify a progress notification handler.
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
        client.DownloadFileAsync(uri, "serverdata.txt");

        Console.WriteLine("Download successful.");

    }
    private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            (string)e.UserState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
    }
    private static void DownloadFileCallback2(object sender, AsyncCompletedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("Download complete");
    }
}

我在这一行中提出了断点:Console.WriteLine("Download complete");但它从未命中过。程序创建空serverdata.txt文件。我在控制台中没有收到有关DownloadProgressCallback下载%的更新。我做错了什么?

2 个答案:

答案 0 :(得分:6)

我没试过,但您可以尝试使用IsBusy属性:

while(client.IsBusy)
     Thread.Sleep(1000);

Console.WriteLine("Download successful.");

或者,如果您使用的是.NET 4.5

,请使用WebClient.DownloadFileTaskAsync方法
client.DownloadFileTaskAsync(uri, "serverdata.txt").Wait();
Console.WriteLine("Download successful.");

答案 1 :(得分:1)

正如其他人使用DownloadFileTaskAsync所做的那样,在等待完成任务时,可以让您的生活更轻松。您可以异步await结果或致电Wait()进行阻止等待。

以下是代码:

private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            ((TaskCompletionSource<object>)e.UserState).Task.AsyncState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
    }

    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri("http://download.thinkbroadband.com/100MB.zip");

        // Specify a progress notification handler.
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
        var task = client.DownloadFileTaskAsync(uri, "serverdata.txt"); // use Task based API

        task.Wait(); // Wait for download to complete, can deadlock in GUI apps

        Console.WriteLine("Download complete");

        Console.WriteLine("Download successful.");
    }

基于GUI的应用程序Wait()调用可能会死锁,但对您的情况来说这很好。