Masuit.Tools:C#硬核開源工具庫!
開源項目地址:https://github.com/XiLife-OSPC/Masuit.Tools
該庫目前全網累計已經超越3000+star。

1.功能主要覆蓋:
數據庫操作:內存表操作、關系實體映射等;
日期時間常用操作:農歷操作、時間戳操作,時分秒轉換等;
文件操作:大文件操作、文件壓縮與解壓、ini配置文件操作;
硬件操作:獲取電腦各個硬件的性能指標;
Html操作:利用C#對html字符串進行“dom”操作,html的XSS凈化、html標簽操作;
日志組件:高並發可用的高性能日志記錄;
多媒體文件操作:圖片的各種處理;
網絡操作:獲取線程內唯一對象、Session和Cookie的擴展、獲取IP地址詳細信息、緩存操作;
Nosql:僅封裝了Redis的常用操作,mongodb的操作類客戶端獨立分開了;
反射操作:各種對對象的字段屬性和方法的快捷方式;
加密安全:對字符串進行的擴展,包含AES、DES、MD5、hash、SHA1、加鹽等;
字符串擴展:包含驗證碼生成、各種與字符串相關的擴展;
Win32API:包含於Windows系統接口相關的操作封裝;
全局擴展:包含字符串擴展,類型轉換,委托、循環操作、異步操作、正則等。
2.有意思的協議
一旦使用本開源項目以及引用了本項目或包含本項目代碼的公司因為違反勞動法(包括但不限定非法裁員、超時用工、雇佣童工等)在任何法律訴訟中敗訴的,項目作者有權利追討本項目的使用費,或者直接不允許使用任何包含本項目的源代碼!任何性質的外包公司或996公司需要使用本類庫,請聯系作者進行商業授權!其他企業或個人可隨意使用不受限。
該項目已得到JetBrains的支持!
3.安裝程序包
.NET Framework ≥4.6.1
PM> Install-Package Masuit.Tools.Net
.NET Core 3.x
PM> Install-Package Masuit.Tools.Core
4.功能特點
1.檢驗字符串是否是Email、手機號、URL、IP地址、身份證號
bool isEmail="3444764617@qq.com".MatchEmail();
bool isInetAddress = "114.114.114.114".MatchInetAddress();
bool isUrl = "http://masuit.com".MatchUrl();
bool isPhoneNumber = "15205201520".MatchPhoneNumber();
bool isIdentifyCard = "312000199502230660".MatchIdentifyCard();// 校驗中國大陸身份證號
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='/Content/font-awesome/css' rel='stylesheet'/>
<!--[if IE 7]>
<link href='/Content/font-awesome-ie7.min.css' rel='stylesheet'/>
<![endif]-->
<script src='/Scripts/modernizr'></script>
<div id='searchBox' role='search'>
<form action='/packages' method='get'>
<span class='user-actions'><a href='/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="/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); // 7clzi
Console.WriteLine("36進制的7clzi是:" + num); // 12345678
//擴展方法形式調用
var bin=12345678.ToBinary(36);//7clzi
var num="7clzi".FromBinary(36);//12345678
//超大數字的進制轉換
var num = "E6186159D38CD50E0463A55E596336BD".FromBinaryBig(16);
Console.WriteLine(num); // 十進制:305849028665645097422198928560410015421
Console.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);//True
Console.WriteLine("產生100w個id耗時"+time+"s");//1.6639039s
9.產生分布式唯一有序短id
var sf = SnowFlake.GetInstance();
string token = sf.GetUniqueId();// rcofqodori0w
string 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); //True
Console.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);//壓縮成zip
SevenZipCompressor.UnRar(@"D:\Download\test.rar", @"D:\Download\");//解壓rar
SevenZipCompressor.Decompress(@"D:\Download\test.tar", @"D:\Download\");//自動識別解壓壓縮包
SevenZipCompressor.Decompress(@"D:\Download\test.7z", @"D:\Download\");
http://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 aes = "123456".AESEncrypt();// AES加密為密文
string s = aes.AESDecrypt(); //AES解密為明文
string aes = "123456".AESEncrypt("abc");// AES密鑰加密為密文
string s = aes.AESDecrypt("abc"); //AES密鑰解密為明文
string enc = "123456".DesEncrypt();// DES加密為密文
string s = enc.DesDecrypt(); //DES解密為明文
string enc = "123456".DesEncrypt("abcdefgh");// DES密鑰加密為密文
string s = enc.DesDecrypt("abcdefgh"); //DES密鑰解密為明文
RsaKey rsaKey = RsaCrypt.GenerateRsaKeys();// 生成RSA密鑰對
string encrypt = "123456".RSAEncrypt(rsaKey.PublicKey);// 公鑰加密
string s = encrypt.RSADecrypt(rsaKey.PrivateKey);// 私鑰解密
string s = "123".Crc32();// 生成crc32摘要
string s = "123".Crc64();// 生成crc64摘要
20.實體校驗
public class MyClass
{
[IsEmail]
public string Email { get; set; }
[IsPhone]
public string PhoneNumber { get; set; }
[IsIPAddress]
public string IP { get; set; }
[MinValue(0, ErrorMessage = "年齡最小為0歲"), MaxValue(100, ErrorMessage = "年齡最大100歲")]
public int Age { get; set; }
[ComplexPassword]//密碼復雜度校驗
public string Password { get; set; }
}
21.HTML操作
List<string> srcs = "html".MatchImgSrcs().ToList();// 獲取html字符串里所有的img標簽的src屬性
var imgTags = "html".MatchImgTags();//獲取html字符串里的所有的img標簽
...
22.DateTime擴展
double milliseconds = DateTime.Now.GetTotalMilliseconds();// 獲取毫秒級時間戳
double microseconds = DateTime.Now.GetTotalMicroseconds();// 獲取微秒級時間戳
double nanoseconds = DateTime.Now.GetTotalNanoseconds();// 獲取納秒級時間戳
double seconds = DateTime.Now.GetTotalSeconds();// 獲取秒級時間戳
double minutes = DateTime.Now.GetTotalMinutes();// 獲取分鍾級時間戳
...
23.IP地址和URL
bool inRange = "192.168.2.2".IpAddressInRange("192.168.1.1","192.168.3.255");// 判斷IP地址是否在這個地址段里
bool isPrivateIp = "172.16.23.25".IsPrivateIP();// 判斷是否是私有地址
bool isExternalAddress = "http://baidu.com".IsExternalAddress();// 判斷是否是外網的URL
//以下需要配置baiduAK
string isp = "114.114.114.114".GetISP(); // 獲取ISP運營商信息
PhysicsAddress physicsAddress = "114.114.114.114".GetPhysicsAddressInfo().Result;// 獲取詳細地理信息對象
Tuple<string, List<string>> ipAddressInfo = "114.114.114.114".GetIPAddressInfo().Result;// 獲取詳細地理信息集合
24.元素去重
var list = new List<MyClass>()
{
new MyClass()
{
Email = "1@1.cn"
},
new MyClass()
{
Email = "1@1.cn"
},
new MyClass()
{
Email = "1@1.cn"
}
};
List<MyClass> classes = list.DistinctBy(c => c.Email).ToList();
Console.WriteLine(classes.Count==1);//True
26.枚舉擴展
public enum MyEnum
{
[Display(Name = "讀")]
[Description("讀")]
Read,
[Display(Name = "寫")]
[Description("寫")]
Write
}
Dictionary<int, string> dic1 = typeof(MyEnum).GetDictionary();// 獲取枚舉值和字符串表示的字典映射
var dic2 = typeof(MyEnum).GetDescriptionAndValue();// 獲取字符串表示和枚舉值的字典映射
string desc = MyEnum.Read.GetDescription();// 獲取Description標簽
string display = MyEnum.Read.GetDisplay();// 獲取Display標簽的Name屬性
var value = typeof(MyEnum).GetValue("Read");//獲取字符串表示值對應的枚舉值
string enumString = 0.ToEnumString(typeof(MyEnum));// 獲取枚舉值對應的字符串表示
27.定長隊列實現
LimitedQueue<string> queue = new LimitedQueue<string>(32);// 聲明一個容量為32個元素的定長隊列
ConcurrentLimitedQueue<string> queue = new ConcurrentLimitedQueue<string>(32);// 聲明一個容量為32個元素的線程安全的定長隊列
28.反射操作
MyClass myClass = new MyClass();
PropertyInfo[] properties = myClass.GetProperties();// 獲取屬性列表
myClass.SetProperty("Email","1@1.cn");//給對象設置值
//動態增刪對象的屬性
MyClass myClass = new MyClass();
var mc = myClass.AddProperty(new List<ClassHelper.CustPropertyInfo>()
{
new ClassHelper.CustPropertyInfo(typeof(string), "Name", "張三"),
new ClassHelper.CustPropertyInfo(typeof(double), "Number", 123456.0),
});//添加屬性
object newObj = mc.DeleteProperty(new List<string>() { "Email", "Age", "IP", "PhoneNumber" });// 刪除屬性
Console.WriteLine(newObj.ToJsonString());// {"Password":null,"Name":"張三","Number":123456.0}
29.獲取線程內唯一對象
CallContext<T>.SetData("db",dbContext);//設置線程內唯一對象
CallContext<T>.GetData("db");//獲取線程內唯一對象
http://30.asp.net core 獲取靜態的HttpContext對象
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddStaticHttpContext();
// ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseStaticHttpContext();
// ...
}
public async Task<IActionResult> Index()
{
HttpContext context = HttpContext2.Current;
}
31.郵件發送
new Email()
{
SmtpServer = "smtp.masuit.com",// SMTP服務器
SmtpPort = 25, // SMTP服務器端口
EnableSsl = true,//使用SSL
Username = "admin@masuit.com",// 郵箱用戶名
Password = "123456",// 郵箱密碼
Tos = "10000@qq.com,10001@qq.com", //收件人
Subject = "測試郵件",//郵件標題
Body = "你好啊",//郵件內容
}.SendAsync(s =>
{
Console.WriteLine(s);// 發送成功后的回調
});// 異步發送郵件
32.圖像的簡單處理
ImageUtilities.CompressImage(@"F:\src\1.jpg", @"F:\dest\2.jpg");//無損壓縮圖片
"base64".SaveDataUriAsImageFile();// 將Base64編碼轉換成圖片
Image image = Image.FromFile(@"D:\1.jpg");
image.MakeThumbnail(@"D:\2.jpg", 120, 80, ThumbnailCutMode.LockWidth);//生成縮略圖
Bitmap bmp = new Bitmap(@"D:\1.jpg");
Bitmap newBmp = bmp.BWPic(bmp.Width, bmp.Height);//轉換成黑白
Bitmap newBmp = bmp.CutAndResize(new Rectangle(0, 0, 1600, 900), 160, 90);//裁剪並縮放
bmp.RevPicLR(bmp.Width, bmp.Height);//左右鏡像
bmp.RevPicUD(bmp.Width, bmp.Height);//上下鏡像
33.隨機數
Random rnd = new Random();
int num = rnd.StrictNext();//產生真隨機數
double gauss = rnd.NextGauss(20,5);//產生正態分布的隨機數