using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO.Enumeration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using AngleSharp.Dom;
using MongoDB.Bson;
namespace Dpz.Core.Infrastructure;
public static class DpzAppBuilderExtensions
{
/// <summary>
/// 生成MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GenerateMd5(this string str)
{
var bytes = MD5.HashData(Encoding.Default.GetBytes(str));
return BitConverter.ToString(bytes).Replace("-", "");
}
/// <summary>
/// 生成MD5 小写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GenerateHashMd5(this string str)
{
var result = string.Join(
"",
from x in MD5.HashData(Encoding.Default.GetBytes(str))
select x.ToString("x2")
);
return result;
}
/// <summary>
/// 将当前时间转换为时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long ToTimeStamp(this DateTime dateTime)
{
var timeSpan =
dateTime.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
var timeStamp = (long)timeSpan.TotalSeconds;
return timeStamp;
}
/// <summary>
/// 遍历集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
/// <summary>
/// 获取集合的下标
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="item"></param>
/// <returns></returns>
public static int IndexOf<T>(this IEnumerable<T> source, T item)
{
var array = source.ToArray();
return Array.IndexOf(array, item);
}
/// <summary>
/// 将时间戳转换为DateTime
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime ToDateTime(this long timeStamp)
{
var utcTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(timeStamp);
return utcTime.LocalDateTime;
}
/// <summary>
/// 从Html中获取所有图片
/// </summary>
/// <param name="images"></param>
/// <returns></returns>
public static List<string> ToImages(this IHtmlCollection<IElement> images)
{
return images
.Select(x => x.Attributes["src"])
.Where(x => x != null)
.Select(x => x!.Value.Split('/'))
.Where(x => x.Length > 0)
.Select(x =>
{
ObjectId.TryParse(x.Last(), out var id);
return id;
})
.Where(x => x != ObjectId.Empty)
.Select(x => x.ToString())
.ToList();
}
/// <summary>
/// 从Html中获取所有图片
/// </summary>
/// <param name="images"></param>
/// <returns></returns>
public static List<ObjectId> ToObjectIdImages(this IHtmlCollection<IElement> images)
{
return images
.Select(x => x.Attributes["src"])
.Where(x => x != null)
.Select(x => x!.Value.Split('/'))
.Where(x => x.Length > 0)
.Select(x =>
{
ObjectId.TryParse(x.Last(), out var id);
return id;
})
.Where(x => x != ObjectId.Empty)
.ToList();
}
/// <summary>
/// 只替换第一次匹配的指定的字符串,
/// </summary>
/// <param name="str"></param>
/// <param name="oldStr">需要替换的字符串</param>
/// <param name="newStr">新字符</param>
/// <returns></returns>
public static string ReplaceOne(this string str, string oldStr, string newStr)
{
var index = str.IndexOf(oldStr, StringComparison.Ordinal);
if (index >= 0)
{
return string.Concat(str.AsSpan(0, index), newStr, str.AsSpan(index + oldStr.Length));
}
return str;
}
public static bool WildCardMatch(this string wildCard, string value)
{
return wildCard.Equals(value, StringComparison.OrdinalIgnoreCase)
|| FileSystemName.MatchesSimpleExpression(wildCard, value);
// var reg = "^" + Regex.Escape(wildCard).Replace("\\?", ".").Replace("\\*", ".*") + "$";
// return Regex.IsMatch(value, reg);
}
public static string ToQueryString(this NameValueCollection? collection)
{
if (collection == null || collection.Count == 0)
{
return "";
}
var sb = new StringBuilder();
var keys = collection.AllKeys;
for (var i = 0; i < collection.Count; i++)
{
var key = keys[i];
var values = collection.GetValues(key);
if (values == null)
{
continue;
}
foreach (var value in values)
{
if (!string.IsNullOrEmpty(key))
{
sb.Append(key).Append('=');
}
sb.Append(HttpUtility.UrlEncode(value)).Append('&');
}
}
return sb.ToString(0, sb.Length - 1);
}
public static byte[] Base64StringToBytes(string base64String)
{
var buffer = new byte[
(base64String.Length * 3 + 3) / 4
- (
base64String.Length > 0 && base64String[^1] == '='
? base64String.Length > 1 && base64String[^2] == '='
? 2
: 1
: 0
)
];
return Convert.TryFromBase64String(base64String, buffer, out _) ? buffer : [];
}
public static string ToSha256Hash(string input)
{
var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(hashBytes).Replace("-", "");
}
}
⚠⚠ 以下内容为AI分析的结果,请根据实际情况进行判断。
代码解释
这是一个 C# 静态扩展类,提供了一系列实用的扩展方法,用于简化日常开发中的常见操作。以下是详细说明:
主要功能分类
1. 加密与哈希方法
GenerateMd5(string): 生成字符串的 MD5 哈希值(大写,带连字符)GenerateHashMd5(string): 生成字符串的 MD5 哈希值(小写,无连字符)ToSha256Hash(string): 生成字符串的 SHA256 哈希值(大写)
2. 时间戳转换方法
ToTimeStamp(DateTime): 将 DateTime 转换为 Unix 时间戳(秒)ToDateTime(long): 将 Unix 时间戳转换为本地 DateTime
3. 集合操作扩展
ForEach<T>(IEnumerable<T>, Action<T>): 遍历集合并对每个元素执行指定操作IndexOf<T>(IEnumerable<T>, T): 获取元素在集合中的索引位置
4. HTML 图片提取方法
ToImages(IHtmlCollection<IElement>): 从 HTML 元素集合中提取图片 URL,解析为 MongoDB ObjectId 字符串列表ToObjectIdImages(IHtmlCollection<IElement>): 同上,但返回 ObjectId 对象列表
这些方法假设图片 URL 的最后一部分是 MongoDB ObjectId。
5. 字符串操作方法
ReplaceOne(string, string, string): 只替换字符串中第一次出现的指定子串WildCardMatch(string, string): 通配符匹配(支持*和?),使用文件系统匹配规则
6. URL 与编码方法
ToQueryString(NameValueCollection): 将 NameValueCollection 转换为 URL 查询字符串格式- 自动处理多值键
- 自动 URL 编码
Base64StringToBytes(string): 将 Base64 字符串转换为字节数组- 预先计算缓冲区大小以提高性能
- 处理填充字符(
=)
技术特点
- 性能优化: 使用
AsSpan减少字符串分配,使用预计算缓冲区 - 空值安全: 多处进行 null 检查和空集合处理
- LINQ 链式调用: 充分利用 LINQ 进行数据转换
- 现代 C# 特性: 使用索引器
[^1]、范围操作符、集合表达式[]
使用场景
这个工具类适用于 Web 应用开发,特别是需要处理加密、时间戳、HTML 解析、MongoDB 集成的场景。
AI 正在分析代码…
评论加载中...