我正在嘗試從 url 下載如下檔案。如果除錯代碼檔案下載成功沒有除錯它給出0位元組檔案。我在這里缺少什么?
由于某些業務邏輯,我無法使用異步
public void download_attachments(string file_id)
{
var client = new HttpClient();
var response = client.GetAsync(@"https://xxxxxxxxxx/api/Attachments/DownloadAttachment/" file_id).Result;
using (var fs = new FileStream(@"C:\d\" Regex.Replace(response.Content.Headers.ContentDisposition.FileName, @"(\[|""|\])", ""), FileMode.CreateNew))
{
response.Content.CopyToAsync(fs);
}
}
uj5u.com熱心網友回復:
您可能會遇到此問題,因為該方法在完成回傳的任務之前退出CopyToAsync()。
要么讓你的方法異步
public async Task download_attachments(string file_id)
{
var client = new HttpClient();
var response = await client.GetAsync(@"https://xxxxxxxxxx/api/Attachments/DownloadAttachment/" file_id);
// WARNING: potential directory traversal vulnerability
using (var fs = new FileStream(@"C:\d\" Regex.Replace(response.Content.Headers.ContentDisposition.FileName, @"(\[|""|\])", ""), FileMode.CreateNew))
{
await response.Content.CopyToAsync(fs);
}
}
或使用同步方法CopyTo()。
public void download_attachments(string file_id)
{
var client = new HttpClient();
var response = client.GetAsync(@"https://xxxxxxxxxx/api/Attachments/DownloadAttachment/" file_id).Result;
// WARNING: potential directory traversal vulnerability
using (var fs = new FileStream(@"C:\d\" Regex.Replace(response.Content.Headers.ContentDisposition.FileName, @"(\[|""|\])", ""), FileMode.CreateNew))
{
response.Content.CopyTo(fs, null, default);
}
}
如果您繼續走同步路線,最好避免使用 Async 方法并找到client.GetAsync().
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452580.html
標籤:C# 。网 httpclient
