下载文件时,我收到来自Web API调用的响应

在我的代码中,我正在调用一个应该用文件(excel)回答我的api,我想将此文件保存在我的PC中,我尝试了此处提供的许多解决方案,但对我来说似乎没有任何作用

CancellationTokenSource
wowkaka7788414 回答:下载文件时,我收到来自Web API调用的响应

获得响应后(假设您得到byte[]),您需要将其保存到本地驱动器。您可以使用File.WriteAllBytes保存。

var saveDir = Path.Combine(Path.GetTempPath(),"some_excel.xlsx");
using (var client = new HttpClient())
{
    var response = client.PostAsync(url,content).Result;
    if (response.IsSuccessStatusCode)
    {
        var content = response.Content.ReadAsByteArrayAsync().Result;
        File.WriteAllBytes(saveDir,content);
    }
}
,

您可以将WebClientDownloadFileAsync方法一起使用

https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadfileasync?redirectedfrom=MSDN&view=netframework-4.8#System_Net_WebClient_DownloadFileAsync_System_Uri_System_String_

本文链接:https://www.f2er.com/3160756.html

大家都在问