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)
{
}
}发布于 2016-09-07 21:40:11
您需要在异步下载完成时保持程序运行,因为它在另一个线程中运行。
尝试类似这样的操作,并等待它显示已完成,然后按enter键结束程序:
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");
}主线程需要在后台线程下载文件时保持运行,这取决于你在哪种类型的应用中使用它。
发布于 2016-09-07 22:09:34
通过将Main函数声明为async,您还可以将DownloadFileTaskAsync与await一起使用。
public static async void Main(string[] args)
{
var urlAddress = "http://mywebsite.com/msexceldoc.xlsx";
var fileName = @"D:\1.xlsx";
using (var client = new WebClient())
{
await client.DownloadFileTaskAsync(new Uri(urlAddress), fileName);
}
}https://stackoverflow.com/questions/39371226
复制相似问题