C# Code Snippets

仅作记录,用于 .NET6.0

为 HTMLAgilityPack 的 HtmlWeb 设置 Headers/Cookie/UA

var htmlWeb = new HtmlWeb();
htmlWeb.UserAgent = My.UA;
htmlWeb.PreRequest += request => {
    request.Headers.Add(My.Headers);
    return true;
};

图片/文件下载

var uri = new Uri(someImageUri);
var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);

var path = $"{SomePath}{fileName}{fileExtension}";

var imageBytes = await client.GetByteArrayAsync(achievement.IconUri);
await File.WriteAllBytesAsync(iconPath, imageBytes);

(新建路径/文件时)去除特殊字符

// 路径
string.Join("_", achievement.Name.Split(Path.GetInvalidPathChars()))
// 文件
string.Join("_", achievement.Name.Split(Path.GetInvalidFileNameChars()))

新建路径中包含 “/” 时防不住,还是要手动过滤

Console 清空本行

string ClearCurrentLine = "\r" + new string(' ', Console.WindowWidth) + "\r";
Console.Write(ClearCurrentLine);

修改图片大小(Resizing Image)

用到了 Magick.NET 库,安装时选择 Magick.NET-Q16-AnyCPU

using ImageMagick;

var size = new MagickGeometry(64, 64);
//size.IgnoreAspectRatio = false/true;

using var image = new MagickImage(imagePath);
image.Resize(size);
await image.WriteAsync(imagePath);

上述代码是通过文件方式打开图片,也可以直接传字节流

using var image = new MagickImage(imageBytes);

与下载图片衔接,实现下载后直接修改大小,然后保存

var uriWithoutQuery = achievement.IconUri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);

var imagePath = $"{fileName}{fileExtension}";

var imageBytes = await client.GetByteArrayAsync(achievement.IconUri);

// Resizing
using var image = new MagickImage(imageBytes);

image.Resize(size);
await image.WriteAsync(imagePath);

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据