.NET 这些年来发生了一些变化,使得这篇文章中的其他答案已经过时了:
- 他们使用来自
System.Drawing 的Image(不适用于.NET Core)来查找图像格式
- 他们使用
System.Net.WebClient,即deprecated
我们不建议您将WebClient 类用于新开发。相反,请使用 System.Net.Http.HttpClient 类。
.NET Core 异步解决方案
获取文件扩展名
获取文件扩展名的第一部分是从 URL 中删除所有不必要的部分。
我们可以使用 Uri.GetLeftPart() 和 UriPartial.Path 来获取从 Scheme 到 Path 的所有内容。
换句话说,https://www.example.com/image.png?query&with.dots 变成了https://www.example.com/image.png。
之后,我们可以使用Path.GetExtension() 仅获取扩展名(在我之前的示例中,.png)。
var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);
下载图片
从这里开始应该是直截了当的。用HttpClient.GetByteArrayAsync下载图片,创建路径,确保目录存在,然后将字节写入File.WriteAllBytesAsync()路径
private async Task DownloadImageAsync(string directoryPath, string fileName, Uri uri)
{
using var httpClient = new HttpClient();
// Get the file extension
var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);
// Create file path and ensure directory exists
var path = Path.Combine(directoryPath, $"{fileName}{fileExtension}");
Directory.CreateDirectory(directoryPath);
// Download the image and write to the file
var imageBytes = await httpClient.GetByteArrayAsync(uri);
await File.WriteAllBytesAsync(path, imageBytes);
}
请注意,您需要以下 using 指令。
using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;
示例用法
var folder = "images";
var fileName = "test";
var url = "https://cdn.discordapp.com/attachments/458291463663386646/592779619212460054/Screenshot_20190624-201411.jpg?query&with.dots";
await DownloadImageAsync(folder, fileName, new Uri(url));
注意事项
- 为每个方法调用创建一个新的
HttpClient 是不好的做法。它应该在整个应用程序中重复使用。我写了一个ImageDownloader(50 行)的简短示例,其中包含更多正确重用HttpClient 并正确处理它的文档,您可以找到here。