gpt4 book ai didi

c# - DownloadFileAsync 不下载文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:52 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的应用程序,它可以从网络上下载一个文件。

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 下载百分比的更新。我做错了什么?

最佳答案

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

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

Console.WriteLine("Download successful.");

或者,使用 WebClient.DownloadFileTaskAsync如果您使用的是 .NET 4.5,则方法

client.DownloadFileTaskAsync(uri, "serverdata.txt").Wait();
Console.WriteLine("Download successful.");

关于c# - DownloadFileAsync 不下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com