.net 如何在C#中从URL下载文件/图像[重复]

anauzrmj  于 2023-05-08  发布在  .NET
关注(0)|答案(1)|浏览(303)

此问题已在此处有答案

How to download a file from a URL in C#?(18回答)
昨天关门了。
我想从一个给定的URL下载一个文件,我认为下面的代码会有所帮助,但不确定它将如何工作或下载文件:

var httpClient = new HttpClient();
var httpRequest = new HttpRequestMessage();

httpRequest.Method = HttpMethod.Get;
httpRequest.Content = new StringContent(string.Empty);
httpRequest.RequestUri = new Uri("https://samplesite.com/attachments=1234");
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpRequest.Headers.TryAddWithoutValidation("Authorization", String.Format("Bearer {0}",""));

var httpResponse = await httpClient.SendAsync(httpRequest);
httpResponse.EnsureSuccessStatusCode();

var mediafile =  await httpResponse.Content.ReadAsStringAsync();

然而,mediafile返回一个HTML代码(不知道为什么),我不知道如何下载和保存图像?另一方面,下面的cURL命令正是所需要的。

curl 'https://samplesite.com/attachments=1234' -H 'Authorization: Bearer ACCESS_TOKEN' > media_file.jpg

上面的cURL命令只是将文件下载到media_file.jpg
有什么帮助吗?

nwlls2ji

nwlls2ji1#

我认为你可以使用'ReadAsStreamAsync'方法来获得图像流,然后将流保存到本地文件

var medisStream = await httpResponse.Content.ReadAsStreamAsync();

 using var fileStream = new FileStream("d://xxx.jpg", FileMode.Create);
 await medisStream.CopyToAsync(fileStream);

相关问题