【发布时间】:2014-07-17 19:40:16
【问题描述】:
我正在尝试编写从网络下载一个文件的简单应用程序。
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 的有关下载百分比的更新。我做错了什么?
【问题讨论】:
-
您的程序在开始下载后立即退出。在下载完成之前,您必须保持它处于活动状态。
-
用
Console.WriteLine("Download successful.");代替Console.ReadLine(); -
您使用异步,以便在下载过程中可以做其他事情。退出程序不是您可以做的其他事情之一:)
-
为什么不尝试在 downloadAsync() 捕获异常并增加超时时间
标签: c#