gpt4 book ai didi

c# - WebClient DownloadFileAsync() 不起作用

转载 作者:行者123 更新时间:2023-11-30 19:55:06 26 4
gpt4 key购买 nike

WebClient DownloadFileAsync() 不适用于相同的 URl 和凭据...

有什么线索吗?

 static void Main(string[] args)
{
try
{
var urlAddress = "http://mywebsite.com/msexceldoc.xlsx";


using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("UserName", "Password");
// It works fine.
client.DownloadFile(urlAddress, @"D:\1.xlsx");
}

/*using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("UserName", "Password");

// It y creats file with 0 bytes. Dunow why is it.
client.DownloadFileAsync(new Uri(urlAddress), @"D:\1.xlsx");
//client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);

}*/
}
catch (Exception ex)
{

}
}

最佳答案

您需要在异步下载完成时保持程序运行,因为它在另一个线程中运行。

尝试这样的操作,等待它说完成,然后按回车键结束程序:

static void Main(string[] args)
{
try
{
var urlAddress = "http://mywebsite.com/msexceldoc.xlsx";

using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("UserName", "Password");

client.DownloadFileAsync(new Uri(urlAddress), @"D:\1.xlsx");
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
}
catch (Exception ex)
{

}

Console.ReadLine();
}

public static void Completed(object o, AsyncCompletedEventArgs args)
{
Console.WriteLine("Completed");
}

根据您在哪种应用中使用它,主线程需要在后台线程下载文件时保持运行。

关于c# - WebClient DownloadFileAsync() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39371226/

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