日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Masuit.Tools,一个免费的轮子

發布時間:2023/12/4 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Masuit.Tools,一个免费的轮子 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

開源地址:

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='/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);// 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("產生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");//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");// 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,3var 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\");

    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] //可在appsetting.json中添加EmailDomainWhiteList配置郵箱域名白名單,逗號分隔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標簽 var str="html".RemoveHtmlTag(); // 去除html標簽 ...

    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

    25.枚舉擴展

    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));// 獲取枚舉值對應的字符串表示

    26.定長隊列實現

    LimitedQueue<string> queue = new LimitedQueue<string>(32);// 聲明一個容量為32個元素的定長隊列 ConcurrentLimitedQueue<string> queue = new ConcurrentLimitedQueue<string>(32);// 聲明一個容量為32個元素的線程安全的定長隊列

    27.反射操作

    MyClass myClass = new MyClass(); PropertyInfo[] properties = myClass.GetProperties();// 獲取屬性列表 myClass.SetProperty("Email","1@1.cn");//給對象設置值

    28.獲取線程內唯一對象

    CallContext<T>.SetData("db",dbContext);//設置線程內唯一對象 CallContext<T>.GetData("db");//獲取線程內唯一對象

    29.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; }

    30.郵件發送

    new Email() {SmtpServer = "smtp.masuit.com",// SMTP服務器SmtpPort = 25, // SMTP服務器端口EnableSsl = true,//使用SSLUsername = "admin@masuit.com",// 郵箱用戶名Password = "123456",// 郵箱密碼Tos = "10000@qq.com,10001@qq.com", //收件人Subject = "測試郵件",//郵件標題Body = "你好啊",//郵件內容 }.SendAsync(s => {Console.WriteLine(s);// 發送成功后的回調 });// 異步發送郵件

    31.圖像的簡單處理

    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);//上下鏡像

    32.隨機數

    Random rnd = new Random(); int num = rnd.StrictNext();//產生真隨機數 double gauss = rnd.NextGauss(20,5);//產生正態分布的隨機數

    33.權重篩選功能

    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();//按權重選出1個元素 var list=data.WeightedItems(2);//按權重選出2個元素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();//按權重選出1個元素 var list = selector.SelectMultiple(3);//按權重選出3個元素

    34.EF Core支持AddOrUpdate方法

    /// <summary> /// 按Id添加或更新文章實體 /// </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.com

    36.集合擴展

    var list = new List<string>() {"1","3","3","3" }; list.AddRangeIf(s => s.Length > 1, "1", "11"); // 將被添加元素中的長度大于1的元素添加到list list.AddRangeIfNotContains("1", "11"); // 將被添加元素中不包含的元素添加到list list.RemoveWhere(s => s.Length<1); // 將集合中長度小于1的元素移除 list.InsertAfter(0, "2"); // 在第一個元素之后插入 list.InsertAfter(s => s == "1", "2"); // 在元素"1"后插入 var dic = list.ToDictionarySafety(s => s); // 安全的轉換成字典類型,當鍵重復時只添加一個鍵 var dic = list.ToConcurrentDictionary(s => s); // 轉換成并發字典類型,當鍵重復時只添加一個鍵 var dic = list.ToDictionarySafety(s => s, s => s.GetHashCode()); // 安全的轉換成字典類型,當鍵重復時只添加一個鍵 dic.AddOrUpdate("4", 4); // 添加或更新鍵值對 dic.AddOrUpdate(new Dictionary<string, int>() {["5"] = 5,["55"]=555 }); // 批量添加或更新鍵值對 dic.AddOrUpdate("5", 6, (s, i) => 66); // 如果是添加,則值為6,若更新則值為66 dic.AddOrUpdate("5", 6, 666); // 如果是添加,則值為6,若更新則值為666 dic.AsConcurrentDictionary(); // 普通字典轉換成并發字典集合 var table=list.ToDataTable(); // 轉換成DataTable類型 table.AddIdentityColumn(); //給DataTable增加一個自增列 table.HasRows(); // 檢查DataTable 是否有數據行 table.ToList<T>(); // datatable轉List var set = list.ToHashSet(s=>s.Name);// 轉HashSet

    37.Mime類型

    var mimeMapper = new MimeMapper(); var mime = mimeMapper.GetExtensionFromMime("image/jpeg"); // .jpg var ext = mimeMapper.GetMimeFromExtension(".jpg"); // image/jpeg

    38.日期時間擴展

    DateTime.Now.GetTotalSeconds(); // 獲取該時間相對于1970-01-01 00:00:00的秒數 DateTime.Now.GetTotalMilliseconds(); // 獲取該時間相對于1970-01-01 00:00:00的毫秒數 DateTime.Now.GetTotalMicroseconds(); // 獲取該時間相對于1970-01-01 00:00:00的微秒數 DateTime.Now.GetTotalNanoseconds(); // 獲取該時間相對于1970-01-01 00:00:00的納秒數 var indate=DateTime.Parse("2020-8-3").In(DateTime.Parse("2020-8-2"),DateTime.Parse("2020-8-4"));//true//時間段計算工具 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")); //連接兩個時間段,結果:2020-8-3~2020-8-6 range.In(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-6"));//判斷是否在某個時間段內,true var (intersected,range2) = range.Intersect(DateTime.Parse("2020-8-4"), DateTime.Parse("2020-8-6"));//兩個時間段是否相交,(true,2020-8-3~2020-8-4) range.Contains(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-4"));//判斷是否包含某個時間段,true ...

    39.流轉換

    stream.SaveAsMemoryStream(); // 任意流轉換成內存流 stream.ToArray(); // 任意流轉換成二進制數組

    40.數值轉換

    1.2345678901.Digits8(); // 將小數截斷為8位 1.23.To<int>(); // 小數轉int 1.23.To<T>(); // 小數轉T基本類型

    41.簡繁轉換

    var str="個體".ToTraditional(); // 轉繁體 var str="個體".ToSimplified(); // 轉簡體

    Asp.Net MVC和Asp.Net Core的支持斷點續傳和多線程下載的ResumeFileResult

    在ASP.NET Core中通過MVC/WebAPI應用程序傳輸文件數據時使用斷點續傳以及多線程下載支持。

    它提供了ETag標頭以及Last-Modified標頭。它還支持以下前置條件標頭:If-Match,If-None-Match,If-Modified-Since,If-Unmodified-Since,If-Range。

    支持 ASP.NET Core 2.0+

    從.NET Core2.0開始,ASP.NET Core內部支持斷點續傳。因此只是對FileResult做了一些擴展。只留下了“Content-Disposition” Inline的一部分。所有代碼都依賴于基礎.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方法調用中配置服務:

    using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;public void ConfigureServices(IServiceCollection services) {services.AddResumeFileResult(); }

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

    總結

    以上是生活随笔為你收集整理的Masuit.Tools,一个免费的轮子的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。