【发布时间】:2015-08-19 20:15:33
【问题描述】:
我正在使用 C# 在 VS15 中制作控制台应用程序。 这是我的下载类:
class DownloadGamefile
{
public void DownloadFile(string address, string location)
{
WebClient client = new WebClient();
Uri Uri = new Uri(address);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
client.DownloadFileAsync(Uri, location);
}
private void DownloadProgress(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 void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == true)
{
Console.WriteLine("Download has been canceled.");
}
else
{
Console.WriteLine("Download completed!");
}
}
}
这是我的主要内容:
class Program
{
static void Main(string[] args)
{
DownloadGamefile DGF = new DownloadGamefile();
DGF.DownloadFile("URL", @"C:\Users\LocDaiLe\Desktop\file.file");
}
}
文件出现在正确的文件夹中,但大小为 0 字节,我的控制台没有显示任何下载进度。
【问题讨论】:
-
可能你的应用在下载完成之前就已经存在,调用
DownloadFile后尝试Console.ReadLine()。 -
感谢您的回复@cDima,但我不明白为什么会这样?我只使用一个控制台应用来测试它。
标签: c# asynchronous download webclient