Masuit.Tools,一個(gè)免費(fèi)的輪子

開源地址:

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,若未配置,則無法調(diào)用GetIPLocation以及GetPhysicalAddress相關(guān)方法

publicStartup(IConfigurationconfiguration)

{

configuration.AddToMasuitTools();// 若未調(diào)用,則默認(rèn)自動(dòng)嘗試加載appsettings.json

}

特色功能示例代碼

1.檢驗(yàn)字符串是否是Email、手機(jī)號(hào)、URL、IP地址、身份證號(hào)

boolisEmail="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",

boolisInetAddress="114.114.114.114".MatchInetAddress();

boolisUrl="http://masuit.com".MatchUrl();

boolisPhoneNumber="15205201520".MatchPhoneNumber();

boolisIdentifyCard="312000199502230660".MatchIdentifyCard();// 校驗(yàn)中國(guó)大陸身份證號(hào)

boolisCNPatentNumber="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)

floatload=SystemInfo.CpuLoad;// 獲取CPU占用率

longphysicalMemory=SystemInfo.PhysicalMemory;// 獲取物理內(nèi)存總數(shù)

longmemoryAvailable=SystemInfo.MemoryAvailable;// 獲取物理內(nèi)存可用率

doublefreePhysicalMemory=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ū)使用率

doubletemperature=SystemInfo.GetCPUTemperature();// 獲取CPU溫度

intcpuCount=SystemInfo.GetCpuCount();// 獲取CPU核心數(shù)

IList<string>ipAddress=SystemInfo.GetIPAddress();// 獲取本機(jī)所有IP地址

stringlocalUsedIp=SystemInfo.GetLocalUsedIP();// 獲取本機(jī)當(dāng)前正在使用的IP地址

IList<string>macAddress=SystemInfo.GetMacAddress();// 獲取本機(jī)所有網(wǎng)卡mac地址

stringosVersion=SystemInfo.GetOsVersion();// 獲取操作系統(tǒng)版本

RamInforamInfo=SystemInfo.GetRamInfo();// 獲取內(nèi)存信息

3.大文件操作

FileStreamfs=newFileStream(@"D:\boot.vmdk",FileMode.OpenOrCreate,FileAccess.ReadWrite);

{

//fs.CopyToFile(@"D:\1.bak");//同步復(fù)制大文件

fs.CopyToFileAsync(@"D:\1.bak");//異步復(fù)制大文件

stringmd5=fs.GetFileMD5Async().Result;//異步獲取文件的MD5

}

4.html的防XSS處理:

stringhtml=@"<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>";

strings=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)算。

NumberFormaternf=newNumberFormater(36);//內(nèi)置2-62進(jìn)制的轉(zhuǎn)換

//NumberFormater nf = new NumberFormater("0123456789abcdefghijklmnopqrstuvwxyz");// 自定義進(jìn)制字符,可用于生成驗(yàn)證碼

strings36=nf.ToString(12345678);

longnum=nf.FromString("7clzi");

Console.WriteLine("12345678的36進(jìn)制是:"+s36);// 7clzi

Console.WriteLine("36進(jìn)制的7clzi是:"+num);// 12345678

//擴(kuò)展方法形式調(diào)用

varbin=12345678.ToBinary(36);//7clzi

varnum="7clzi".FromBinary(36);//12345678

//超大數(shù)字的進(jìn)制轉(zhuǎn)換

varnum="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í)器

HiPerfTimertimer=HiPerfTimer.StartNew();

for(inti=0;i<100000;i++)

{

//todo

}

timer.Stop();

Console.WriteLine("執(zhí)行for循環(huán)100000次耗時(shí)"+timer.Duration+"s");

doubletime=HiPerfTimer.Execute(()=>

{

for(inti=0;i<100000;i++)

{

//todo

}

});

Console.WriteLine("執(zhí)行for循環(huán)100000次耗時(shí)"+time+"s");

8.單機(jī)產(chǎn)生唯一有序的短id

vartoken=Stopwatch.GetTimestamp().ToBinary(36);

varset=newHashSet<string>();

doubletime=HiPerfTimer.Execute(()=>

{

for(inti=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.6639039s

9.產(chǎn)生分布式唯一有序短id

varsf=SnowFlake.GetInstance();

stringtoken=sf.GetUniqueId();// rcofqodori0w

stringshortId=sf.GetUniqueShortId(8);// qodw9728

varset=newHashSet<string>();

doubletime=HiPerfTimer.Execute(()=>

{

for(inti=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.6891495s

10.農(nóng)歷轉(zhuǎn)換

ChineseCalendar.CustomHolidays.Add(DateTime.Parse("2018-12-31"),"元旦節(jié)");//自定義節(jié)假日

ChineseCalendartoday=newChineseCalendar(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();

boolb=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();

boolb=func("abc");// true

12.模版引擎

vartmp=newTemplate("{{name}},你好!");

tmp.Set("name","萬金油");

strings=tmp.Render();//萬金油,你好!

vartmp=newTemplate("{{one}},{{two}},{{three}}");

strings=tmp.Set("one","1").Set("two","2").Set("three","3").Render();// 1,2,3

vartmp=newTemplate("{{name}},{{greet}}!");

tmp.Set("name","萬金油");

strings=tmp.Render();// throw 模版變量{{greet}}未被使用

13.List轉(zhuǎn)Datatable

varlist=newList<MyClass>()

{

newMyClass()

{

Name="張三",

Age=22

},

newMyClass()

{

Name="李四",

Age=21

},

newMyClass()

{

Name="王五",

Age=28

}

};

vartable=list.Select(c=>new{姓名=c.Name,年齡=c.Age}).ToList().ToDataTable();// 將自動(dòng)填充列姓名和年齡

14.文件壓縮解壓

.NET Framework

MemoryStreamms=SevenZipCompressor.ZipStream(newList<string>()

{

@"D:\1.txt",

"http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg",

});//壓縮成內(nèi)存流

SevenZipCompressor.Zip(newList<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

privatereadonlyISevenZipCompressor_sevenZipCompressor;

publicTest(ISevenZipCompressorsevenZipCompressor)

{

_sevenZipCompressor=sevenZipCompressor;

}

使用方式同.NET Framework版本

15.日志組件

LogManager.LogDirectory=AppDomain.CurrentDomain.BaseDirectory+"/logs";

LogManager.Event+=info=>

{

//todo:注冊(cè)一些事件操作

};

LogManager.Info("記錄一次消息");

LogManager.Error(newException("異常消息"));

16.FTP客戶端

FtpClientftpClient=FtpClient.GetAnonymousClient("192.168.2.2");//創(chuàng)建一個(gè)匿名訪問的客戶端

//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)下載

varmtd=newMultiThreadDownloader("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)=>

{

vardownloader=senderasMultiThreadDownloader;

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客戶端操作類

vartcpClient=newTcpClient(AddressFamily.InterNetwork);

Socketsocket=tcpClient.ConnectSocket(IPAddress.Any,5000);

socket.SendFile("D:\\test\\1.txt",false,i=>

{

Console.WriteLine("已發(fā)送"+i+"%");

});

19.加密解密

varenc="123456".MDString();// MD5加密

varenc="123456".MDString("abc");// MD5加鹽加密

varenc="123456".MDString2();// MD5兩次加密

varenc="123456".MDString2("abc");// MD5兩次加鹽加密

varenc="123456".MDString3();// MD5三次加密

varenc="123456".MDString3("abc");// MD5三次加鹽加密

stringaes="123456".AESEncrypt();// AES加密為密文

strings=aes.AESDecrypt();//AES解密為明文

stringaes="123456".AESEncrypt("abc");// AES密鑰加密為密文

strings=aes.AESDecrypt("abc");//AES密鑰解密為明文

stringenc="123456".DesEncrypt();// DES加密為密文

strings=enc.DesDecrypt();//DES解密為明文

stringenc="123456".DesEncrypt("abcdefgh");// DES密鑰加密為密文

strings=enc.DesDecrypt("abcdefgh");//DES密鑰解密為明文

RsaKeyrsaKey=RsaCrypt.GenerateRsaKeys();// 生成RSA密鑰對(duì)

stringencrypt="123456".RSAEncrypt(rsaKey.PublicKey);// 公鑰加密

strings=encrypt.RSADecrypt(rsaKey.PrivateKey);// 私鑰解密

strings="123".Crc32();// 生成crc32摘要

strings="123".Crc64();// 生成crc64摘要

20.實(shí)體校驗(yàn)

publicclassMyClass

{

[IsEmail]//可在appsetting.json中添加EmailDomainWhiteList配置郵箱域名白名單,逗號(hào)分隔

publicstringEmail{get;set;}

[IsPhone]

publicstringPhoneNumber{get;set;}

[IsIPAddress]

publicstringIP{get;set;}

[MinValue(0,ErrorMessage="年齡最小為0歲"),MaxValue(100,ErrorMessage="年齡最大100歲")]

publicintAge{get;set;}

[ComplexPassword]//密碼復(fù)雜度校驗(yàn)

publicstringPassword{get;set;}

}

21.HTML操作

List<string>srcs="html".MatchImgSrcs().ToList();// 獲取html字符串里所有的img標(biāo)簽的src屬性

varimgTags="html".MatchImgTags();//獲取html字符串里的所有的img標(biāo)簽

varstr="html".RemoveHtmlTag();// 去除html標(biāo)簽

...

22.DateTime擴(kuò)展

doublemilliseconds=DateTime.Now.GetTotalMilliseconds();// 獲取毫秒級(jí)時(shí)間戳

doublemicroseconds=DateTime.Now.GetTotalMicroseconds();// 獲取微秒級(jí)時(shí)間戳

doublenanoseconds=DateTime.Now.GetTotalNanoseconds();// 獲取納秒級(jí)時(shí)間戳

doubleseconds=DateTime.Now.GetTotalSeconds();// 獲取秒級(jí)時(shí)間戳

doubleminutes=DateTime.Now.GetTotalMinutes();// 獲取分鐘級(jí)時(shí)間戳

...

23.IP地址和URL

boolinRange="192.168.2.2".IpAddressInRange("192.168.1.1","192.168.3.255");// 判斷IP地址是否在這個(gè)地址段里

boolisPrivateIp="172.16.23.25".IsPrivateIP();// 判斷是否是私有地址

boolisExternalAddress="http://baidu.com".IsExternalAddress();// 判斷是否是外網(wǎng)的URL

//以下需要配置baiduAK

stringisp="114.114.114.114".GetISP();// 獲取ISP運(yùn)營(yíng)商信息

PhysicsAddressphysicsAddress="114.114.114.114".GetPhysicsAddressInfo().Result;// 獲取詳細(xì)地理信息對(duì)象

Tuple<string,List<string>>ipAddressInfo="114.114.114.114".GetIPAddressInfo().Result;// 獲取詳細(xì)地理信息集合

24.元素去重

varlist=newList<MyClass>()

{

newMyClass()

{

Email="1@1.cn"

},

newMyClass()

{

Email="1@1.cn"

},

newMyClass()

{

Email="1@1.cn"

}

};

List<MyClass>classes=list.DistinctBy(c=>c.Email).ToList();

Console.WriteLine(classes.Count==1);//True

25.枚舉擴(kuò)展

publicenumMyEnum

{

[Display(Name="讀")]

[Description("讀")]

Read,


[Display(Name="寫")]

[Description("寫")]

Write

}

Dictionary<int,string>dic1=typeof(MyEnum).GetDictionary();// 獲取枚舉值和字符串表示的字典映射

vardic2=typeof(MyEnum).GetDescriptionAndValue();// 獲取字符串表示和枚舉值的字典映射

stringdesc=MyEnum.Read.GetDescription();// 獲取Description標(biāo)簽

stringdisplay=MyEnum.Read.GetDisplay();// 獲取Display標(biāo)簽的Name屬性

varvalue=typeof(MyEnum).GetValue("Read");//獲取字符串表示值對(duì)應(yīng)的枚舉值

stringenumString=0.ToEnumString(typeof(MyEnum));// 獲取枚舉值對(duì)應(yīng)的字符串表示

26.定長(zhǎng)隊(duì)列實(shí)現(xiàn)

LimitedQueue<string>queue=newLimitedQueue<string>(32);// 聲明一個(gè)容量為32個(gè)元素的定長(zhǎng)隊(duì)列

ConcurrentLimitedQueue<string>queue=newConcurrentLimitedQueue<string>(32);// 聲明一個(gè)容量為32個(gè)元素的線程安全的定長(zhǎng)隊(duì)列

27.反射操作

MyClassmyClass=newMyClass();

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

publicvoidConfigureServices(IServiceCollectionservices)

{

// ...

services.AddStaticHttpContext();

// ...

}

publicvoidConfigure(IApplicationBuilderapp,IHostingEnvironmentenv)

{

// ...

app.UseStaticHttpContext();

// ...

}

publicasyncTask<IActionResult>Index()

{

HttpContextcontext=HttpContext2.Current;

}

30.郵件發(fā)送

newEmail()

{

SmtpServer="smtp.masuit.com",// SMTP服務(wù)器

SmtpPort=25,// SMTP服務(wù)器端口

EnableSsl=true,//使用SSL

Username="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");//無損壓縮圖片

"base64".SaveDataUriAsImageFile();// 將Base64編碼轉(zhuǎn)換成圖片

Imageimage=Image.FromFile(@"D:\1.jpg");

image.MakeThumbnail(@"D:\2.jpg",120,80,ThumbnailCutMode.LockWidth);//生成縮略圖

Bitmapbmp=newBitmap(@"D:\1.jpg");

BitmapnewBmp=bmp.BWPic(bmp.Width,bmp.Height);//轉(zhuǎn)換成黑白

BitmapnewBmp=bmp.CutAndResize(newRectangle(0,0,1600,900),160,90);//裁剪并縮放

bmp.RevPicLR(bmp.Width,bmp.Height);//左右鏡像

bmp.RevPicUD(bmp.Width,bmp.Height);//上下鏡像

32.隨機(jī)數(shù)

Randomrnd=newRandom();

intnum=rnd.StrictNext();//產(chǎn)生真隨機(jī)數(shù)

doublegauss=rnd.NextGauss(20,5);//產(chǎn)生正態(tài)分布的隨機(jī)數(shù)

33.權(quán)重篩選功能

vardata=newList<WeightedItem<string>>()

{

newWeightedItem<string>("A",1),

newWeightedItem<string>("B",3),

newWeightedItem<string>("C",4),

newWeightedItem<string>("D",4),

};

varitem=data.WeightedItem();//按權(quán)重選出1個(gè)元素

varlist=data.WeightedItems(2);//按權(quán)重選出2個(gè)元素

varselector=newWeightedSelector<string>(newList<WeightedItem<string>>()

{

newWeightedItem<string>("A",1),

newWeightedItem<string>("B",3),

newWeightedItem<string>("C",4),

newWeightedItem<string>("D",4),

});

varitem=selector.Select();//按權(quán)重選出1個(gè)元素

varlist=selector.SelectMultiple(3);//按權(quán)重選出3個(gè)元素

34.EF Core支持AddOrUpdate方法

/// <summary>

/// 按Id添加或更新文章實(shí)體

/// </summary>

publicoverridePostSavePost(Postt)

{

DataContext.Set<Post>().AddOrUpdate(t=>t.Id,t);

returnt;

}

35.敏感信息掩碼

"13123456789".Mask();// 131****5678

"admin@masuit.com".MaskEmail();// a****n@masuit.com

36.集合擴(kuò)展

varlist=newList<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"后插入

vardic=list.ToDictionarySafety(s=>s);// 安全的轉(zhuǎn)換成字典類型,當(dāng)鍵重復(fù)時(shí)只添加一個(gè)鍵

vardic=list.ToConcurrentDictionary(s=>s);// 轉(zhuǎn)換成并發(fā)字典類型,當(dāng)鍵重復(fù)時(shí)只添加一個(gè)鍵

vardic=list.ToDictionarySafety(s=>s,s=>s.GetHashCode());// 安全的轉(zhuǎn)換成字典類型,當(dāng)鍵重復(fù)時(shí)只添加一個(gè)鍵

dic.AddOrUpdate("4",4);// 添加或更新鍵值對(duì)

dic.AddOrUpdate(newDictionary<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ā)字典集合

vartable=list.ToDataTable();// 轉(zhuǎn)換成DataTable類型

table.AddIdentityColumn();//給DataTable增加一個(gè)自增列

table.HasRows();// 檢查DataTable 是否有數(shù)據(jù)行

table.ToList<T>();// datatable轉(zhuǎn)List

varset=list.ToHashSet(s=>s.Name);// 轉(zhuǎn)HashSet

37.Mime類型

varmimeMapper=newMimeMapper();

varmime=mimeMapper.GetExtensionFromMime("image/jpeg");// .jpg

varext=mimeMapper.GetMimeFromExtension(".jpg");// image/jpeg

38.日期時(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ù)

varindate=DateTime.Parse("2020-8-3").In(DateTime.Parse("2020-8-2"),DateTime.Parse("2020-8-4"));//true

//時(shí)間段計(jì)算工具

varrange=newDateTimeRange(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)換

varstr="個(gè)體".ToTraditional();// 轉(zhuǎn)繁體

varstr="個(gè)體".ToSimplified();// 轉(zhuǎn)簡(jiǎn)體

Asp.Net MVC和Asp.Net Core的支持?jǐn)帱c(diǎn)續(xù)傳和多線程下載的ResumeFileResult

在ASP.NET Core中通過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一樣的方式使用它。

usingMasuit.Tools.Mvc;

usingMasuit.Tools.Mvc.ResumeFileResult;

privatereadonlyMimeMappermimeMapper=newMimeMapper();// 推薦使用依賴注入

publicActionResultResumeFileResult()

{

varpath=Server.MapPath("~/Content/test.mp4");

returnnewResumeFileResult(path,mimeMapper.GetMimeFromPath(path),Request);

}

publicActionResultResumeFile()

{

returnthis.ResumeFile("~/Content/test.mp4",mimeMapper.GetMimeFromPath(path),"test.mp4");

}

publicActionResultResumePhysicalFile()

{

returnthis.ResumePhysicalFile(@"D:/test.mp4",mimeMapper.GetMimeFromPath(@"D:/test.mp4"),"test.mp4");

}

Asp.Net Core

要使用ResumeFileResults,必須在Startup.cs的ConfigureServices方法調(diào)用中配置服務(wù):

usingMasuit.Tools.AspNetCore.ResumeFileResults.Extensions;

publicvoidConfigureServices(IServiceCollectionservices)

{

services.AddResumeFileResult();

}

然后在你的控制器中,你可以像在FileResult一樣的方式使用它。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容