开源地址:
https://gitee.com/masuit/Masuit.Tools
包含一些常用的操作类,大都是静态类,加密解密,反射操作,动态编译,权重随机筛选算法,简繁转换,分布式短id,表达式树,linq扩展,文件压缩,多线程下载和FTP客户端,硬件信息,字符串扩展方法,日期时间扩展操作,中国农历,大文件拷贝,图像裁剪,验证码,断点续传,实体映射、集合扩展等常用封装。
建议开发环境
操作系统:Windows 10 1903及以上版本
开发工具:VisualStudio2019 v16.5及以上版本
SDK:.Net Core 3.1.0及以上版本
安装程序包
.NET Framework ≥4.6.1
PM> Install-Package Masuit.Tools.Net
.NET Core 2.x/3.x
PM> Install-Package Masuit.Tools.Core
为工具库注册配置
工具库需要用到外部配置节:
EmailDomainWhiteList,邮箱校验需要用到的白名单域名,英文逗号分隔,每个元素支持正则表达式,若未配置,则不启用邮箱校验白名单
EmailDomainBlockList,邮箱校验需要用到的黑名单域名,英文逗号分隔,每个元素支持正则表达式,且黑名单优先级高于白名单,若未配置,则不启用邮箱校验黑白名单
BaiduAK,获取IP/地理位置相关百度云APIKey,若未配置,则无法调用GetIPLocation以及GetPhysicalAddress相关方法
public Startup(IConfiguration configuration){ configuration.AddToMasuitTools(); // 若未调用,则默认自动尝试加载appsettings.json}
特色功能示例代码
1.检验字符串是否是Email、手机号、URL、IP地址、身份证号
bool isEmail="3444764617@qq.com".MatchEmail(); // 可在appsetting.json中添加EmailDomainWhiteList和EmailDomainBlockList配置邮箱域名黑白名单,逗号分隔,如"EmailDomainBlockList": "^\\w{1,5}@qq.com,^\\w{1,5}@163.com,^\\w{1,5}@gmail.com,^\\w{1,5}@outlook.com",bool isInetAddress = "114.114.114.114".MatchInetAddress();bool isUrl = "http://masuit.com".MatchUrl();bool isPhoneNumber = "15205201520".MatchPhoneNumber();bool isIdentifyCard = "312000199502230660".MatchIdentifyCard();// 校验中国大陆身份证号bool isCNPatentNumber = "200410018477.9".MatchCNPatentNumber(); // 校验中国专利申请号或专利号,是否带校验位,校验位前是否带“.”,都可以校验,待校验的号码前不要带CN、ZL字样的前缀
2.硬件监测(仅支持Windows)
float load = SystemInfo.CpuLoad;// 获取CPU占用率long physicalMemory = SystemInfo.PhysicalMemory;// 获取物理内存总数long memoryAvailable = SystemInfo.MemoryAvailable;// 获取物理内存可用率double freePhysicalMemory = SystemInfo.GetFreePhysicalMemory();// 获取可用物理内存Dictionary<string, string> diskFree = SystemInfo.DiskFree();// 获取磁盘每个分区可用空间Dictionary<string, string> diskTotalSpace = SystemInfo.DiskTotalSpace();// 获取磁盘每个分区总大小Dictionary<string, double> diskUsage = SystemInfo.DiskUsage();// 获取磁盘每个分区使用率double temperature = SystemInfo.GetCPUTemperature();// 获取CPU温度int cpuCount = SystemInfo.GetCpuCount();// 获取CPU核心数IList<string> ipAddress = SystemInfo.GetIPAddress();// 获取本机所有IP地址string localUsedIp = SystemInfo.GetLocalUsedIP();// 获取本机当前正在使用的IP地址IList<string> macAddress = SystemInfo.GetMacAddress();// 获取本机所有网卡mac地址string osVersion = SystemInfo.GetOsVersion();// 获取操作系统版本RamInfo ramInfo = SystemInfo.GetRamInfo();// 获取内存信息
3.大文件操作
FileStream fs = new FileStream(@"D:\boot.vmdk", FileMode.OpenOrCreate, FileAccess.ReadWrite);{ //fs.CopyToFile(@"D:\1.bak");//同步复制大文件 fs.CopyToFileAsync(@"D:\1.bak");//异步复制大文件 string md5 = fs.GetFileMD5Async().Result;//异步获取文件的MD5}
4.html的防XSS处理:
string html = @"<link href='https://www.cnblogs.com//Content/font-awesome/css' rel='stylesheet'/> <!--[if IE 7]> <link href='https://www.cnblogs.com//Content/font-awesome-ie7.min.css' rel='stylesheet'/> <![endif]--> <script src='https://www.cnblogs.com//Scripts/modernizr'></script> <div id='searchBox' role='search'> <form action='/packages' method='get'> <span class='user-actions'><a href='https://www.cnblogs.com//users/account/LogOff'>退出</a></span> <input name='q' id='searchBoxInput'/> <input id='searchBoxSubmit' type='submit' value='Submit' /> </form> </div>";string s = html.HtmlSantinizerStandard();//清理后:<div><span><a href="https://www.cnblogs.com//users/account/LogOff">退出</a></span></div>
5.整理操作系统的内存:
Windows.ClearMemorySilent();
6.任意进制转换
可用于生成短id,短hash等操作,纯数学运算。
NumberFormater nf = new NumberFormater(36);//内置2-62进制的转换//NumberFormater nf = new NumberFormater("0123456789abcdefghijklmnopqrstuvwxyz");// 自定义进制字符,可用于生成验证码string s36 = nf.ToString(12345678);long num = nf.FromString("7clzi");Console.WriteLine("12345678的36进制是:" + s36); // 7clziConsole.WriteLine("36进制的7clzi是:" + num); // 12345678
//扩展方法形式调用var bin=12345678.ToBinary(36);//7clzivar num="7clzi".FromBinary(36);//12345678
//超大数字的进制转换var num = "E6186159D38CD50E0463A55E596336BD".FromBinaryBig(16);Console.WriteLine(num); // 十进制:305849028665645097422198928560410015421Console.WriteLine(num.ToBinary(64)); // 64进制:3C665pQUPl3whzFlVpoPqZ,22位长度Console.WriteLine(num.ToBinary(36)); // 36进制:dmed4dkd5bhcg4qdktklun0zh,25位长度
7.纳秒级性能计时器
HiPerfTimer timer = HiPerfTimer.StartNew();for (int i = 0; i < 100000; i++){ //todo}timer.Stop();Console.WriteLine("执行for循环100000次耗时"+timer.Duration+"s");
double time = HiPerfTimer.Execute(() =>{ for (int i = 0; i < 100000; i++) { //todo }});Console.WriteLine("执行for循环100000次耗时"+time+"s");
8.单机产生唯一有序的短id
var token=Stopwatch.GetTimestamp().ToBinary(36);
var set = new HashSet<string>();double time = HiPerfTimer.Execute(() =>{ for (int i = 0; i < 1000000; i++) { set.Add(Stopwatch.GetTimestamp().ToBinary(36)); }});Console.WriteLine(set.Count==1000000);//TrueConsole.WriteLine("产生100w个id耗时"+time+"s");//1.6639039s
9.产生分布式唯一有序短id
var sf = SnowFlake.GetInstance();string token = sf.GetUniqueId();// rcofqodori0wstring shortId = sf.GetUniqueShortId(8);// qodw9728
var set = new HashSet<string>();double time = HiPerfTimer.Execute(() =>{ for (int i = 0; i < 1000000; i++) { set.Add(SnowFlake.GetInstance().GetUniqueId()); }});Console.WriteLine(set.Count == 1000000); //TrueConsole.WriteLine("产生100w个id耗时" + time + "s"); //2.6891495s
10.农历转换
ChineseCalendar.CustomHolidays.Add(DateTime.Parse("2018-12-31"),"元旦节");//自定义节假日ChineseCalendar today = new ChineseCalendar(DateTime.Parse("2018-12-31"));Console.WriteLine(today.ChineseDateString);// 二零一八年十一月廿五Console.WriteLine(today.AnimalString);// 生肖:狗Console.WriteLine(today.GanZhiDateString);// 干支:戊戌年甲子月丁酉日Console.WriteLine(today.DateHoliday);// 获取按公历计算的节假日...
11.Linq表达式树扩展
Expression<Func<string, bool>> where1 = s => s.StartsWith("a");Expression<Func<string, bool>> where2 = s => s.Length > 10;Func<string, bool> func = where1.And(where2).Compile();bool b=func("abcd12345678");//true
Expression<Func<string, bool>> where1 = s => s.StartsWith("a");Expression<Func<string, bool>> where2 = s => s.Length > 10;Func<string, bool> func = where1.Or(where2).Compile();bool b=func("abc");// true
12.模版引擎
var tmp = new Template("{{name}},你好!");tmp.Set("name", "万金油");string s = tmp.Render();//万金油,你好!
var tmp = new Template("{{one}},{{two}},{{three}}");string s = tmp.Set("one", "1").Set("two", "2").Set("three", "3").Render();// 1,2,3
var tmp = new Template("{{name}},{{greet}}!");tmp.Set("name", "万金油");string s = tmp.Render();// throw 模版变量{{greet}}未被使用
13.List转Datatable
var list = new List<MyClass>(){ new MyClass() { Name = "张三", Age = 22 }, new MyClass() { Name = "李四", Age = 21 }, new MyClass() { Name = "王五", Age = 28 }};var table = list.Select(c => new{姓名=c.Name,年龄=c.Age}).ToList().ToDataTable();// 将自动填充列姓名和年龄
14.文件压缩解压
.NET Framework
MemoryStream ms = SevenZipCompressor.ZipStream(new List<string>(){ @"D:\1.txt", "http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg",});//压缩成内存流
SevenZipCompressor.Zip(new List<string>(){ @"D:\1.txt", "http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg",}, zip);//压缩成zipSevenZipCompressor.UnRar(@"D:\Download\test.rar", @"D:\Download\");//解压rarSevenZipCompressor.Decompress(@"D:\Download\test.tar", @"D:\Download\");//自动识别解压压缩包SevenZipCompressor.Decompress(@"D:\Download\test.7z", @"D:\Download\");
ASP.NET Core
Startup.cs
services.AddSevenZipCompressor();
构造函数注入ISevenZipCompressor
private readonly ISevenZipCompressor _sevenZipCompressor;public Test(ISevenZipCompressor sevenZipCompressor){ _sevenZipCompressor = sevenZipCompressor;}
使用方式同.NET Framework版本
15.日志组件
LogManager.LogDirectory=AppDomain.CurrentDomain.BaseDirectory+"/logs";LogManager.Event+=info =>{ //todo:注册一些事件操作};LogManager.Info("记录一次消息");LogManager.Error(new Exception("异常消息"));
16.FTP客户端
FtpClient ftpClient = FtpClient.GetAnonymousClient("192.168.2.2");//创建一个匿名访问的客户端//FtpClient ftpClient = FtpClient.GetClient("192.168.2.3","admin","123456");// 创建一个带用户名密码的客户端ftpClient.Delete("/1.txt");// 删除文件ftpClient.Download("/test/2.txt","D:\\test\\2.txt");// 下载文件ftpClient.UploadFile("/test/22.txt","D:\\test\\22.txt",(sum, progress) =>{ Console.WriteLine("已上传:"+progress*1.0/sum);});//上传文件并检测进度List<string> files = ftpClient.GetFiles("/");//列出ftp服务端文件列表...
17.多线程后台下载
var mtd = new MultiThreadDownloader("https://attachments-cdn.shimo.im/yXwC4kphjVQu06rH/KeyShot_Pro_7.3.37.7z",Environment.GetEnvironmentVariable("temp"),"E:\\Downloads\\KeyShot_Pro_7.3.37.7z",8);mtd.Configure(req => { req.Referer = "https://masuit.com"; req.Headers.Add("Origin", "https://baidu.com");});mtd.TotalProgressChanged+=(sender, e) =>{ var downloader = sender as MultiThreadDownloader; Console.WriteLine("下载进度:"+downloader.TotalProgress+"%"); Console.WriteLine("下载速度:"+downloader.TotalSpeedInBytes/1024/1024+"MBps");};mtd.FileMergeProgressChanged+=(sender, e) =>{ Console.WriteLine("下载完成");};mtd.Start();//开始下载//mtd.Pause(); // 暂停下载//mtd.Resume(); // 继续下载
18.Socket客户端操作类
var tcpClient = new TcpClient(AddressFamily.InterNetwork);Socket socket = tcpClient.ConnectSocket(IPAddress.Any,5000);socket.SendFile("D:\\test\\1.txt",false,i =>{ Console.WriteLine("已发送"+i+"%");});
19.加密解密
var enc="123456".MDString();// MD5加密var enc="123456".MDString("abc");// MD5加盐加密var enc="123456".MDString2();// MD5两次加密var enc="123456".MDString2("abc");// MD5两次加盐加密var enc="123456".MDString3();// MD5三次加密var enc="123456".MDString3("abc");// MD5三次加盐加密string ae.........