使用httpClient同步下载文件
Download file synchronously with httpClient
我有从这个网站借来的代码 (https://psycodedeveloper.wordpress.com/2013/04/02/how-to-download-a-file-with-httpclient-in-c/):
public static Task DownloadAsync(string requestUri, string filename)
{
if (requestUri == null)
throw new ArgumentNullException("requestUri");
return DownloadAsync(new Uri(requestUri), filename);
}
public static async Task DownloadAsync(Uri requestUri, string filename)
{
if (filename == null)
throw new ArgumentNullException("filename");
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
using (Stream contentStream = await (await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None, 10000, true))
{
await contentStream.CopyToAsync(stream);
}
}
}
}
我这样称呼它:
DownloadAsync(@"http://www.stafforini.com/docs/Covey%20-%20The%207%20habits%20of%20highly%20effective%20people.pdf", @"D:\Temp\test.pdf").Wait();
但它没有下载任何文件,而且实际上从未完成下载。
这段代码有什么问题?
编辑1
答案是死锁,但我不知道它有死锁,所以感谢你让我知道我的代码有死锁,我现在明白了并且可以修复它。
这不是另一个问题的重复,因为我不知道为什么它不起作用,如果我知道,那个答案会对我有帮助
此代码会在任何具有同步上下文的环境(除控制台应用程序以外的大多数环境)中死锁,因为它会产生循环等待。
如果你在这样的环境中工作,你应该使用async/await "all the way down."
有关详细信息,请参阅 Stephen Cleary 的 Don't Block on Async Code。
此代码仅存储从 URL 下载的文件。
您必须将数据从 FileStream 保存到文件中。
John Skeet 对此 link 的回答是一个简短的例子:
How do I save a stream to a file in C#?
我有从这个网站借来的代码 (https://psycodedeveloper.wordpress.com/2013/04/02/how-to-download-a-file-with-httpclient-in-c/):
public static Task DownloadAsync(string requestUri, string filename)
{
if (requestUri == null)
throw new ArgumentNullException("requestUri");
return DownloadAsync(new Uri(requestUri), filename);
}
public static async Task DownloadAsync(Uri requestUri, string filename)
{
if (filename == null)
throw new ArgumentNullException("filename");
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
using (Stream contentStream = await (await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None, 10000, true))
{
await contentStream.CopyToAsync(stream);
}
}
}
}
我这样称呼它:
DownloadAsync(@"http://www.stafforini.com/docs/Covey%20-%20The%207%20habits%20of%20highly%20effective%20people.pdf", @"D:\Temp\test.pdf").Wait();
但它没有下载任何文件,而且实际上从未完成下载。
这段代码有什么问题?
编辑1
答案是死锁,但我不知道它有死锁,所以感谢你让我知道我的代码有死锁,我现在明白了并且可以修复它。
这不是另一个问题的重复,因为我不知道为什么它不起作用,如果我知道,那个答案会对我有帮助
此代码会在任何具有同步上下文的环境(除控制台应用程序以外的大多数环境)中死锁,因为它会产生循环等待。
如果你在这样的环境中工作,你应该使用async/await "all the way down."
有关详细信息,请参阅 Stephen Cleary 的 Don't Block on Async Code。
此代码仅存储从 URL 下载的文件。 您必须将数据从 FileStream 保存到文件中。
John Skeet 对此 link 的回答是一个简短的例子: How do I save a stream to a file in C#?