Masuit.Tools,一个免费的轮子
開源地址:
https://gitee.com/masuit/Masuit.Tools
包含一些常用的操作類,大都是靜態(tài)類,加密解密,反射操作,動(dòng)態(tài)編譯,權(quán)重隨機(jī)篩選算法,簡(jiǎn)繁轉(zhuǎn)換,分布式短id,表達(dá)式樹,linq擴(kuò)展,文件壓縮,多線程下載和FTP客戶端,硬件信息,字符串?dāng)U展方法,日期時(shí)間擴(kuò)展操作,中國(guó)農(nóng)歷,大文件拷貝,圖像裁剪,驗(yàn)證碼,斷點(diǎn)續(xù)傳,實(shí)體映射、集合擴(kuò)展等常用封裝。
建議開發(fā)環(huán)境
操作系統(tǒng):Windows 10 1903及以上版本
開發(fā)工具: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為工具庫(kù)注冊(cè)配置
工具庫(kù)需要用到外部配置節(jié):
EmailDomainWhiteList,郵箱校驗(yàn)需要用到的白名單域名,英文逗號(hào)分隔,每個(gè)元素支持正則表達(dá)式,若未配置,則不啟用郵箱校驗(yàn)白名單
EmailDomainBlockList,郵箱校驗(yàn)需要用到的黑名單域名,英文逗號(hào)分隔,每個(gè)元素支持正則表達(dá)式,且黑名單優(yōu)先級(jí)高于白名單,若未配置,則不啟用郵箱校驗(yàn)黑白名單
BaiduAK,獲取IP/地理位置相關(guān)百度云APIKey,若未配置,則無(wú)法調(diào)用GetIPLocation以及GetPhysicalAddress相關(guān)方法
特色功能示例代碼
1.檢驗(yàn)字符串是否是Email、手機(jī)號(hào)、URL、IP地址、身份證號(hào)
bool isEmail="3444764617@qq.com".MatchEmail(); // 可在appsetting.json中添加EmailDomainWhiteList和EmailDomainBlockList配置郵箱域名黑白名單,逗號(hào)分隔,如"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();// 校驗(yàn)中國(guó)大陸身份證號(hào) bool isCNPatentNumber = "200410018477.9".MatchCNPatentNumber(); // 校驗(yàn)中國(guó)專利申請(qǐng)?zhí)柣驅(qū)@?hào),是否帶校驗(yàn)位,校驗(yàn)位前是否帶“.”,都可以校驗(yàn),待校驗(yàn)的號(hào)碼前不要帶CN、ZL字樣的前綴2.硬件監(jiān)測(cè)(僅支持Windows)
float load = SystemInfo.CpuLoad;// 獲取CPU占用率 long physicalMemory = SystemInfo.PhysicalMemory;// 獲取物理內(nèi)存總數(shù) long memoryAvailable = SystemInfo.MemoryAvailable;// 獲取物理內(nèi)存可用率 double freePhysicalMemory = SystemInfo.GetFreePhysicalMemory();// 獲取可用物理內(nèi)存 Dictionary<string, string> diskFree = SystemInfo.DiskFree();// 獲取磁盤每個(gè)分區(qū)可用空間 Dictionary<string, string> diskTotalSpace = SystemInfo.DiskTotalSpace();// 獲取磁盤每個(gè)分區(qū)總大小 Dictionary<string, double> diskUsage = SystemInfo.DiskUsage();// 獲取磁盤每個(gè)分區(qū)使用率 double temperature = SystemInfo.GetCPUTemperature();// 獲取CPU溫度 int cpuCount = SystemInfo.GetCpuCount();// 獲取CPU核心數(shù) IList<string> ipAddress = SystemInfo.GetIPAddress();// 獲取本機(jī)所有IP地址 string localUsedIp = SystemInfo.GetLocalUsedIP();// 獲取本機(jī)當(dāng)前正在使用的IP地址 IList<string> macAddress = SystemInfo.GetMacAddress();// 獲取本機(jī)所有網(wǎng)卡mac地址 string osVersion = SystemInfo.GetOsVersion();// 獲取操作系統(tǒng)版本 RamInfo ramInfo = SystemInfo.GetRamInfo();// 獲取內(nèi)存信息3.大文件操作
FileStream fs = new FileStream(@"D:\boot.vmdk", FileMode.OpenOrCreate, FileAccess.ReadWrite); {//fs.CopyToFile(@"D:\1.bak");//同步復(fù)制大文件fs.CopyToFileAsync(@"D:\1.bak");//異步復(fù)制大文件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.整理操作系統(tǒng)的內(nèi)存:
Windows.ClearMemorySilent();6.任意進(jìn)制轉(zhuǎn)換
可用于生成短id,短hash等操作,純數(shù)學(xué)運(yùn)算。
NumberFormater nf = new NumberFormater(36);//內(nèi)置2-62進(jìn)制的轉(zhuǎn)換 //NumberFormater nf = new NumberFormater("0123456789abcdefghijklmnopqrstuvwxyz");// 自定義進(jìn)制字符,可用于生成驗(yàn)證碼 string s36 = nf.ToString(12345678); long num = nf.FromString("7clzi"); Console.WriteLine("12345678的36進(jìn)制是:" + s36); // 7clzi Console.WriteLine("36進(jìn)制的7clzi是:" + num); // 12345678//擴(kuò)展方法形式調(diào)用 var bin=12345678.ToBinary(36);//7clzi var num="7clzi".FromBinary(36);//12345678//超大數(shù)字的進(jìn)制轉(zhuǎn)換 var num = "E6186159D38CD50E0463A55E596336BD".FromBinaryBig(16); Console.WriteLine(num); // 十進(jìn)制:305849028665645097422198928560410015421 Console.WriteLine(num.ToBinary(64)); // 64進(jìn)制:3C665pQUPl3whzFlVpoPqZ,22位長(zhǎng)度 Console.WriteLine(num.ToBinary(36)); // 36進(jìn)制:dmed4dkd5bhcg4qdktklun0zh,25位長(zhǎng)度7.納秒級(jí)性能計(jì)時(shí)器
HiPerfTimer timer = HiPerfTimer.StartNew(); for (int i = 0; i < 100000; i++) {//todo } timer.Stop(); Console.WriteLine("執(zhí)行for循環(huán)100000次耗時(shí)"+timer.Duration+"s");double time = HiPerfTimer.Execute(() => {for (int i = 0; i < 100000; i++){//todo} }); Console.WriteLine("執(zhí)行for循環(huán)100000次耗時(shí)"+time+"s");8.單機(jī)產(chǎn)生唯一有序的短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("產(chǎn)生100w個(gè)id耗時(shí)"+time+"s");//1.6639039s9.產(chǎn)生分布式唯一有序短id
var sf = SnowFlake.GetInstance(); string token = sf.GetUniqueId();// rcofqodori0w string shortId = sf.GetUniqueShortId(8);// qodw9728var 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("產(chǎn)生100w個(gè)id耗時(shí)" + time + "s"); //2.6891495s10.農(nóng)歷轉(zhuǎn)換
ChineseCalendar.CustomHolidays.Add(DateTime.Parse("2018-12-31"),"元旦節(jié)");//自定義節(jié)假日 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);// 獲取按公歷計(jì)算的節(jié)假日 ...11.Linq表達(dá)式樹擴(kuò)展
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");//trueExpression<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");// true12.模版引擎
var tmp = new Template("{{name}},你好!"); tmp.Set("name", "萬(wàn)金油"); string s = tmp.Render();//萬(wàn)金油,你好!var tmp = new Template("{{one}},{{two}},{{three}}"); string s = tmp.Set("one", "1").Set("two", "2").Set("three", "3").Render();// 1,2,3var tmp = new Template("{{name}},{{greet}}!"); tmp.Set("name", "萬(wàn)金油"); string s = tmp.Render();// throw 模版變量{{greet}}未被使用13.List轉(zhuǎn)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();// 將自動(dòng)填充列姓名和年齡14.文件壓縮解壓
.NET Framework
MemoryStream ms = SevenZipCompressor.ZipStream(new List<string>() {@"D:\1.txt","http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg", });//壓縮成內(nèi)存流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\");//自動(dòng)識(shí)別解壓壓縮包 SevenZipCompressor.Decompress(@"D:\Download\test.7z", @"D:\Download\");ASP.NET Core
Startup.cs
services.AddSevenZipCompressor();構(gòu)造函數(shù)注入ISevenZipCompressor
private readonly ISevenZipCompressor _sevenZipCompressor; public Test(ISevenZipCompressor sevenZipCompressor) {_sevenZipCompressor = sevenZipCompressor; }使用方式同.NET Framework版本
15.日志組件
LogManager.LogDirectory=AppDomain.CurrentDomain.BaseDirectory+"/logs"; LogManager.Event+=info => {//todo:注冊(cè)一些事件操作 }; LogManager.Info("記錄一次消息"); LogManager.Error(new Exception("異常消息"));16.FTP客戶端
FtpClient ftpClient = FtpClient.GetAnonymousClient("192.168.2.2");//創(chuàng)建一個(gè)匿名訪問(wèn)的客戶端 //FtpClient ftpClient = FtpClient.GetClient("192.168.2.3","admin","123456");// 創(chuàng)建一個(gè)帶用戶名密碼的客戶端 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); });//上傳文件并檢測(cè)進(jìn)度 List<string> files = ftpClient.GetFiles("/");//列出ftp服務(wù)端文件列表 ...17.多線程后臺(tái)下載
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("下載進(jìn)度:"+downloader.TotalProgress+"%");Console.WriteLine("下載速度:"+downloader.TotalSpeedInBytes/1024/1024+"MBps"); }; mtd.FileMergeProgressChanged+=(sender, e) => {Console.WriteLine("下載完成"); }; mtd.Start();//開始下載 //mtd.Pause(); // 暫停下載 //mtd.Resume(); // 繼續(xù)下載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("已發(fā)送"+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密鑰對(duì) string encrypt = "123456".RSAEncrypt(rsaKey.PublicKey);// 公鑰加密 string s = encrypt.RSADecrypt(rsaKey.PrivateKey);// 私鑰解密string s = "123".Crc32();// 生成crc32摘要 string s = "123".Crc64();// 生成crc64摘要20.實(shí)體校驗(yàn)
public class MyClass {[IsEmail] //可在appsetting.json中添加EmailDomainWhiteList配置郵箱域名白名單,逗號(hào)分隔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]//密碼復(fù)雜度校驗(yàn)public string Password { get; set; } }21.HTML操作
List<string> srcs = "html".MatchImgSrcs().ToList();// 獲取html字符串里所有的img標(biāo)簽的src屬性 var imgTags = "html".MatchImgTags();//獲取html字符串里的所有的img標(biāo)簽 var str="html".RemoveHtmlTag(); // 去除html標(biāo)簽 ...22.DateTime擴(kuò)展
double milliseconds = DateTime.Now.GetTotalMilliseconds();// 獲取毫秒級(jí)時(shí)間戳 double microseconds = DateTime.Now.GetTotalMicroseconds();// 獲取微秒級(jí)時(shí)間戳 double nanoseconds = DateTime.Now.GetTotalNanoseconds();// 獲取納秒級(jí)時(shí)間戳 double seconds = DateTime.Now.GetTotalSeconds();// 獲取秒級(jí)時(shí)間戳 double minutes = DateTime.Now.GetTotalMinutes();// 獲取分鐘級(jí)時(shí)間戳 ...23.IP地址和URL
bool inRange = "192.168.2.2".IpAddressInRange("192.168.1.1","192.168.3.255");// 判斷IP地址是否在這個(gè)地址段里 bool isPrivateIp = "172.16.23.25".IsPrivateIP();// 判斷是否是私有地址 bool isExternalAddress = "http://baidu.com".IsExternalAddress();// 判斷是否是外網(wǎng)的URL//以下需要配置baiduAK string isp = "114.114.114.114".GetISP(); // 獲取ISP運(yùn)營(yíng)商信息 PhysicsAddress physicsAddress = "114.114.114.114".GetPhysicsAddressInfo().Result;// 獲取詳細(xì)地理信息對(duì)象 Tuple<string, List<string>> ipAddressInfo = "114.114.114.114".GetIPAddressInfo().Result;// 獲取詳細(xì)地理信息集合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);//True25.枚舉擴(kuò)展
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標(biāo)簽 string display = MyEnum.Read.GetDisplay();// 獲取Display標(biāo)簽的Name屬性 var value = typeof(MyEnum).GetValue("Read");//獲取字符串表示值對(duì)應(yīng)的枚舉值 string enumString = 0.ToEnumString(typeof(MyEnum));// 獲取枚舉值對(duì)應(yīng)的字符串表示26.定長(zhǎng)隊(duì)列實(shí)現(xiàn)
LimitedQueue<string> queue = new LimitedQueue<string>(32);// 聲明一個(gè)容量為32個(gè)元素的定長(zhǎng)隊(duì)列 ConcurrentLimitedQueue<string> queue = new ConcurrentLimitedQueue<string>(32);// 聲明一個(gè)容量為32個(gè)元素的線程安全的定長(zhǎng)隊(duì)列27.反射操作
MyClass myClass = new MyClass(); PropertyInfo[] properties = myClass.GetProperties();// 獲取屬性列表 myClass.SetProperty("Email","1@1.cn");//給對(duì)象設(shè)置值28.獲取線程內(nèi)唯一對(duì)象
CallContext<T>.SetData("db",dbContext);//設(shè)置線程內(nèi)唯一對(duì)象 CallContext<T>.GetData("db");//獲取線程內(nèi)唯一對(duì)象29.asp.net core 獲取靜態(tài)的HttpContext對(duì)象
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; }30.郵件發(fā)送
new Email() {SmtpServer = "smtp.masuit.com",// SMTP服務(wù)器SmtpPort = 25, // SMTP服務(wù)器端口EnableSsl = true,//使用SSLUsername = "admin@masuit.com",// 郵箱用戶名Password = "123456",// 郵箱密碼Tos = "10000@qq.com,10001@qq.com", //收件人Subject = "測(cè)試郵件",//郵件標(biāo)題Body = "你好啊",//郵件內(nèi)容 }.SendAsync(s => {Console.WriteLine(s);// 發(fā)送成功后的回調(diào) });// 異步發(fā)送郵件31.圖像的簡(jiǎn)單處理
ImageUtilities.CompressImage(@"F:\src\1.jpg", @"F:\dest\2.jpg");//無(wú)損壓縮圖片"base64".SaveDataUriAsImageFile();// 將Base64編碼轉(zhuǎn)換成圖片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);//轉(zhuǎn)換成黑白 Bitmap newBmp = bmp.CutAndResize(new Rectangle(0, 0, 1600, 900), 160, 90);//裁剪并縮放 bmp.RevPicLR(bmp.Width, bmp.Height);//左右鏡像 bmp.RevPicUD(bmp.Width, bmp.Height);//上下鏡像32.隨機(jī)數(shù)
Random rnd = new Random(); int num = rnd.StrictNext();//產(chǎn)生真隨機(jī)數(shù) double gauss = rnd.NextGauss(20,5);//產(chǎn)生正態(tài)分布的隨機(jī)數(shù)33.權(quán)重篩選功能
var data=new List<WeightedItem<string>>() {new WeightedItem<string>("A", 1),new WeightedItem<string>("B", 3),new WeightedItem<string>("C", 4),new WeightedItem<string>("D", 4), }; var item=data.WeightedItem();//按權(quán)重選出1個(gè)元素 var list=data.WeightedItems(2);//按權(quán)重選出2個(gè)元素var selector = new WeightedSelector<string>(new List<WeightedItem<string>>() {new WeightedItem<string>("A", 1),new WeightedItem<string>("B", 3),new WeightedItem<string>("C", 4),new WeightedItem<string>("D", 4), }); var item = selector.Select();//按權(quán)重選出1個(gè)元素 var list = selector.SelectMultiple(3);//按權(quán)重選出3個(gè)元素34.EF Core支持AddOrUpdate方法
/// <summary> /// 按Id添加或更新文章實(shí)體 /// </summary> public override Post SavePost(Post t) {DataContext.Set<Post>().AddOrUpdate(t => t.Id, t);return t; }35.敏感信息掩碼
"13123456789".Mask(); // 131****5678 "admin@masuit.com".MaskEmail(); // a****n@masuit.com36.集合擴(kuò)展
var list = new List<string>() {"1","3","3","3" }; list.AddRangeIf(s => s.Length > 1, "1", "11"); // 將被添加元素中的長(zhǎng)度大于1的元素添加到list list.AddRangeIfNotContains("1", "11"); // 將被添加元素中不包含的元素添加到list list.RemoveWhere(s => s.Length<1); // 將集合中長(zhǎng)度小于1的元素移除 list.InsertAfter(0, "2"); // 在第一個(gè)元素之后插入 list.InsertAfter(s => s == "1", "2"); // 在元素"1"后插入 var dic = list.ToDictionarySafety(s => s); // 安全的轉(zhuǎn)換成字典類型,當(dāng)鍵重復(fù)時(shí)只添加一個(gè)鍵 var dic = list.ToConcurrentDictionary(s => s); // 轉(zhuǎn)換成并發(fā)字典類型,當(dāng)鍵重復(fù)時(shí)只添加一個(gè)鍵 var dic = list.ToDictionarySafety(s => s, s => s.GetHashCode()); // 安全的轉(zhuǎn)換成字典類型,當(dāng)鍵重復(fù)時(shí)只添加一個(gè)鍵 dic.AddOrUpdate("4", 4); // 添加或更新鍵值對(duì) dic.AddOrUpdate(new Dictionary<string, int>() {["5"] = 5,["55"]=555 }); // 批量添加或更新鍵值對(duì) dic.AddOrUpdate("5", 6, (s, i) => 66); // 如果是添加,則值為6,若更新則值為66 dic.AddOrUpdate("5", 6, 666); // 如果是添加,則值為6,若更新則值為666 dic.AsConcurrentDictionary(); // 普通字典轉(zhuǎn)換成并發(fā)字典集合 var table=list.ToDataTable(); // 轉(zhuǎn)換成DataTable類型 table.AddIdentityColumn(); //給DataTable增加一個(gè)自增列 table.HasRows(); // 檢查DataTable 是否有數(shù)據(jù)行 table.ToList<T>(); // datatable轉(zhuǎn)List var set = list.ToHashSet(s=>s.Name);// 轉(zhuǎn)HashSet37.Mime類型
var mimeMapper = new MimeMapper(); var mime = mimeMapper.GetExtensionFromMime("image/jpeg"); // .jpg var ext = mimeMapper.GetMimeFromExtension(".jpg"); // image/jpeg38.日期時(shí)間擴(kuò)展
DateTime.Now.GetTotalSeconds(); // 獲取該時(shí)間相對(duì)于1970-01-01 00:00:00的秒數(shù) DateTime.Now.GetTotalMilliseconds(); // 獲取該時(shí)間相對(duì)于1970-01-01 00:00:00的毫秒數(shù) DateTime.Now.GetTotalMicroseconds(); // 獲取該時(shí)間相對(duì)于1970-01-01 00:00:00的微秒數(shù) DateTime.Now.GetTotalNanoseconds(); // 獲取該時(shí)間相對(duì)于1970-01-01 00:00:00的納秒數(shù) var indate=DateTime.Parse("2020-8-3").In(DateTime.Parse("2020-8-2"),DateTime.Parse("2020-8-4"));//true//時(shí)間段計(jì)算工具 var range = new DateTimeRange(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-5")); range.Union(DateTime.Parse("2020-8-4"), DateTime.Parse("2020-8-6")); //連接兩個(gè)時(shí)間段,結(jié)果:2020-8-3~2020-8-6 range.In(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-6"));//判斷是否在某個(gè)時(shí)間段內(nèi),true var (intersected,range2) = range.Intersect(DateTime.Parse("2020-8-4"), DateTime.Parse("2020-8-6"));//兩個(gè)時(shí)間段是否相交,(true,2020-8-3~2020-8-4) range.Contains(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-4"));//判斷是否包含某個(gè)時(shí)間段,true ...39.流轉(zhuǎn)換
stream.SaveAsMemoryStream(); // 任意流轉(zhuǎn)換成內(nèi)存流 stream.ToArray(); // 任意流轉(zhuǎn)換成二進(jìn)制數(shù)組40.數(shù)值轉(zhuǎn)換
1.2345678901.Digits8(); // 將小數(shù)截?cái)酁?位 1.23.To<int>(); // 小數(shù)轉(zhuǎn)int 1.23.To<T>(); // 小數(shù)轉(zhuǎn)T基本類型41.簡(jiǎn)繁轉(zhuǎn)換
var str="個(gè)體".ToTraditional(); // 轉(zhuǎn)繁體 var str="個(gè)體".ToSimplified(); // 轉(zhuǎn)簡(jiǎn)體Asp.Net MVC和Asp.Net Core的支持?jǐn)帱c(diǎn)續(xù)傳和多線程下載的ResumeFileResult
在ASP.NET Core中通過(guò)MVC/WebAPI應(yīng)用程序傳輸文件數(shù)據(jù)時(shí)使用斷點(diǎn)續(xù)傳以及多線程下載支持。
它提供了ETag標(biāo)頭以及Last-Modified標(biāo)頭。它還支持以下前置條件標(biāo)頭:If-Match,If-None-Match,If-Modified-Since,If-Unmodified-Since,If-Range。
支持 ASP.NET Core 2.0+
從.NET Core2.0開始,ASP.NET Core內(nèi)部支持?jǐn)帱c(diǎn)續(xù)傳。因此只是對(duì)FileResult做了一些擴(kuò)展。只留下了“Content-Disposition” Inline的一部分。所有代碼都依賴于基礎(chǔ).NET類。
如何使用
.NET Framework
在你的控制器中,你可以像在FileResult一樣的方式使用它。
using Masuit.Tools.Mvc; using Masuit.Tools.Mvc.ResumeFileResult;private readonly MimeMapper mimeMapper=new MimeMapper(); // 推薦使用依賴注入public ActionResult ResumeFileResult() {var path = Server.MapPath("~/Content/test.mp4");return new ResumeFileResult(path, mimeMapper.GetMimeFromPath(path), Request); }public ActionResult ResumeFile() {return this.ResumeFile("~/Content/test.mp4", mimeMapper.GetMimeFromPath(path), "test.mp4"); }public ActionResult ResumePhysicalFile() {return this.ResumePhysicalFile(@"D:/test.mp4", mimeMapper.GetMimeFromPath(@"D:/test.mp4"), "test.mp4"); }Asp.Net Core
要使用ResumeFileResults,必須在Startup.cs的ConfigureServices方法調(diào)用中配置服務(wù):
using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;public void ConfigureServices(IServiceCollection services) {services.AddResumeFileResult(); }然后在你的控制器中,你可以像在FileResult一樣的方式使用它。
總結(jié)
以上是生活随笔為你收集整理的Masuit.Tools,一个免费的轮子的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: .NET | 多线程下的调用上下文 :
- 下一篇: NET问答: 如何取消或中止 Task