1
1
Эх сурвалжийг харах

升级语言版本到C#8.0

懒得勤快 6 жил өмнө
parent
commit
f9cb9031e0
54 өөрчлөгдсөн 2001 нэмэгдсэн , 2530 устгасан
  1. 2 2
      Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Controllers/TestController.cs
  2. 1 0
      Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.csproj
  3. 2 1
      Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Startup.cs
  4. 2 0
      Masuit.Tools.Core.UnitTest/Masuit.Tools.Core.UnitTest.csproj
  5. 5 12
      Masuit.Tools.Core/Database/DataTableHelper.cs
  6. 1 1
      Masuit.Tools.Core/Extensions.cs
  7. 18 27
      Masuit.Tools.Core/Files/FileExt.cs
  8. 33 48
      Masuit.Tools.Core/Hardware/SystemInfo.cs
  9. 2 4
      Masuit.Tools.Core/Logging/LogManager.cs
  10. 1 1
      Masuit.Tools.Core/Mapping/Core/MapperConfigurationCollectionContainer.cs
  11. 1 0
      Masuit.Tools.Core/Masuit.Tools.Core.csproj
  12. 0 7
      Masuit.Tools.Core/Masuit.Tools.Core.xml
  13. 221 325
      Masuit.Tools.Core/Media/ImageUtilities.cs
  14. 22 27
      Masuit.Tools.Core/Models/Email.cs
  15. 136 194
      Masuit.Tools.Core/Net/FtpClient.cs
  16. 24 33
      Masuit.Tools.Core/Net/MultiThreadDownloader.cs
  17. 93 84
      Masuit.Tools.Core/Net/SocketClient.cs
  18. 77 77
      Masuit.Tools.Core/Net/WebExtension.cs
  19. 116 174
      Masuit.Tools.Core/Security/Encrypt.cs
  20. 11 19
      Masuit.Tools.Core/Security/RSACrypt.cs
  21. 41 47
      Masuit.Tools.Core/Strings/ValidateCode.cs
  22. 5 5
      Masuit.Tools.Core/Systems/EnumExt.cs
  23. 1 1
      Masuit.Tools.Core/Systems/SnowFlake.cs
  24. 73 103
      Masuit.Tools.Core/Win32/Windows.cs
  25. 20 22
      Masuit.Tools.Core/Win32/WindowsCommand.cs
  26. 1 0
      Masuit.Tools.ExpressionMapperBenchmark/Masuit.Tools.ExpressionMapperBenchmark.csproj
  27. 1 0
      Masuit.Tools.NoSQL.MongoDBClient/Masuit.Tools.NoSQL.MongoDBClient.csproj
  28. 1 1
      Masuit.Tools.UnitTest/ExtensionMethodsTest.cs
  29. 2 0
      Masuit.Tools.UnitTest/Masuit.Tools.UnitTest.csproj
  30. 5 12
      Masuit.Tools/Database/DataTableHelper.cs
  31. 18 27
      Masuit.Tools/Files/FileExt.cs
  32. 94 70
      Masuit.Tools/Hardware/SystemInfo.cs
  33. 2 4
      Masuit.Tools/Logging/LogManager.cs
  34. 1 1
      Masuit.Tools/Mapping/Core/MapperConfigurationCollectionContainer.cs
  35. 5 0
      Masuit.Tools/Masuit.Tools.csproj
  36. 2 0
      Masuit.Tools/Masuit.Tools.csproj.DotSettings
  37. 221 273
      Masuit.Tools/Media/ImageUtilities.cs
  38. 22 27
      Masuit.Tools/Models/Email.cs
  39. 136 194
      Masuit.Tools/Net/FtpClient.cs
  40. 24 33
      Masuit.Tools/Net/MultiThreadDownloader.cs
  41. 93 84
      Masuit.Tools/Net/SocketClient.cs
  42. 168 201
      Masuit.Tools/Net/WebExtension.cs
  43. 116 174
      Masuit.Tools/Security/Encrypt.cs
  44. 11 19
      Masuit.Tools/Security/RSACrypt.cs
  45. 42 47
      Masuit.Tools/Strings/ValidateCode.cs
  46. 1 1
      Masuit.Tools/Systems/EnumExt.cs
  47. 1 1
      Masuit.Tools/Systems/SnowFlake.cs
  48. 74 104
      Masuit.Tools/Win32/Windows.cs
  49. 20 22
      Masuit.Tools/Win32/WindowsCommand.cs
  50. 16 13
      Masuit.Tools/app.config
  51. 1 0
      NetCoreTest/NetCoreTest.csproj
  52. 3 2
      NetCoreTest/Startup.cs
  53. 10 6
      Test/App.config
  54. 2 0
      Test/Test.csproj

+ 2 - 2
Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Controllers/TestController.cs

@@ -15,7 +15,7 @@ namespace Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.Controllers
     {
         private const string EntityTag = "\"TestFile\"";
 
-        private readonly IHostingEnvironment _hostingEnvironment;
+        private readonly IWebHostEnvironment _hostingEnvironment;
 
         private readonly DateTimeOffset _lastModified = new DateTimeOffset(2016, 1, 1, 0, 0, 0, TimeSpan.Zero);
 
@@ -23,7 +23,7 @@ namespace Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.Controllers
         /// 
         /// </summary>
         /// <param name="hostingEnvironment"></param>
-        public TestController(IHostingEnvironment hostingEnvironment)
+        public TestController(IWebHostEnvironment hostingEnvironment)
         {
             _hostingEnvironment = hostingEnvironment;
         }

+ 1 - 0
Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Masuit.Tools.AspNetCore.ResumeFileResults.WebTest.csproj

@@ -5,6 +5,7 @@
     <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
     <RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
     <RunAnalyzersDuringLiveAnalysis>false</RunAnalyzersDuringLiveAnalysis>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

+ 2 - 1
Masuit.Tools.AspNetCore.ResumeFileResults.WebTest/Startup.cs

@@ -8,6 +8,7 @@ using Microsoft.OpenApi.Models;
 using System;
 using System.Text.Encodings.Web;
 using System.Text.Unicode;
+using Microsoft.Extensions.Hosting;
 
 namespace Masuit.Tools.AspNetCore.ResumeFileResults.WebTest
 {
@@ -46,7 +47,7 @@ namespace Masuit.Tools.AspNetCore.ResumeFileResults.WebTest
             }); //解决razor视图中中文被编码的问题
         }
 
-        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
         {
             if (env.IsDevelopment())
             {

+ 2 - 0
Masuit.Tools.Core.UnitTest/Masuit.Tools.Core.UnitTest.csproj

@@ -4,6 +4,8 @@
     <TargetFramework>netcoreapp3.0</TargetFramework>
 
     <IsPackable>false</IsPackable>
+
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
   <ItemGroup>

+ 5 - 12
Masuit.Tools.Core/Database/DataTableHelper.cs

@@ -51,21 +51,14 @@ namespace Masuit.Tools.Core.Database
         public static List<T> ToList<T>(this DataTable dt) where T : class, new()
         {
             List<T> list = new List<T>();
-            using (dt)
+            if (dt == null || dt.Rows.Count == 0)
             {
-                if (dt == null || dt.Rows.Count == 0)
-                {
-                    return list;
-                }
-
-                DataTableBuilder<T> eblist = DataTableBuilder<T>.CreateBuilder(dt.Rows[0]);
-                foreach (DataRow info in dt.Rows)
-                {
-                    list.Add(eblist.Build(info));
-                }
-
                 return list;
             }
+
+            list.AddRange(dt.Rows.Cast<DataRow>().Select(info => DataTableBuilder<T>.CreateBuilder(dt.Rows[0]).Build(info)));
+
+            return list;
         }
 
         /// <summary>

+ 1 - 1
Masuit.Tools.Core/Extensions.cs

@@ -1241,7 +1241,7 @@ namespace Masuit.Tools
                 isMatch = true;
                 return new Uri(s);
             }
-            catch (Exception e)
+            catch
             {
                 isMatch = false;
                 return null;

+ 18 - 27
Masuit.Tools.Core/Files/FileExt.cs

@@ -18,14 +18,12 @@ namespace Masuit.Tools.Files
         /// <param name="bufferSize">缓冲区大小,默认8MB</param>
         public static void CopyToFile(this Stream fs, string dest, int bufferSize = 1024 * 8 * 1024)
         {
-            using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            using var fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            byte[] buf = new byte[bufferSize];
+            int len;
+            while ((len = fs.Read(buf, 0, buf.Length)) != 0)
             {
-                byte[] buf = new byte[bufferSize];
-                int len = 0;
-                while ((len = fs.Read(buf, 0, buf.Length)) != 0)
-                {
-                    fsWrite.Write(buf, 0, len);
-                }
+                fsWrite.Write(buf, 0, len);
             }
         }
 
@@ -37,21 +35,16 @@ namespace Masuit.Tools.Files
         /// <param name="bufferSize">缓冲区大小,默认8MB</param>
         public static async void CopyToFileAsync(this Stream fs, string dest, int bufferSize = 1024 * 1024 * 8)
         {
-            using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            await using FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            byte[] buf = new byte[bufferSize];
+            int len;
+            await Task.Run(() =>
             {
-                byte[] buf = new byte[bufferSize];
-                int len;
-                await Task.Run(() =>
+                while ((len = fs.Read(buf, 0, buf.Length)) != 0)
                 {
-                    using (fs)
-                    {
-                        while ((len = fs.Read(buf, 0, buf.Length)) != 0)
-                        {
-                            fsWrite.Write(buf, 0, len);
-                        }
-                    }
-                }).ConfigureAwait(true);
-            }
+                    fsWrite.Write(buf, 0, len);
+                }
+            }).ConfigureAwait(true);
         }
 
         /// <summary>
@@ -61,13 +54,11 @@ namespace Masuit.Tools.Files
         /// <param name="filename"></param>
         public static void SaveFile(this MemoryStream ms, string filename)
         {
-            using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
-            {
-                byte[] buffer = ms.ToArray(); // 转化为byte格式存储
-                fs.Write(buffer, 0, buffer.Length);
-                fs.Flush();
-                buffer = null;
-            }
+            using var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            byte[] buffer = ms.ToArray(); // 转化为byte格式存储
+            fs.Write(buffer, 0, buffer.Length);
+            fs.Flush();
+            buffer = null;
         }
 
         /// <summary>

+ 33 - 48
Masuit.Tools.Core/Hardware/SystemInfo.cs

@@ -6,6 +6,7 @@ using System.Collections.Generic;
 using System.Diagnostics;
 using System.Management;
 using System.Net;
+using System.Net.Sockets;
 using System.Runtime.InteropServices;
 using System.Text;
 using System.Text.RegularExpressions;
@@ -471,19 +472,13 @@ namespace Masuit.Tools.Hardware
             try
             {
                 IList<string> list = new List<string>();
-                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                using (mc)
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                using var moc = mc.GetInstances();
+                foreach (ManagementObject mo in moc)
                 {
-                    ManagementObjectCollection moc = mc.GetInstances();
-                    using (moc)
+                    if ((bool)mo["IPEnabled"])
                     {
-                        foreach (ManagementObject mo in moc)
-                        {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                list.Add(mo["MacAddress"].ToString());
-                            }
-                        }
+                        list.Add(mo["MacAddress"].ToString());
                     }
                 }
 
@@ -505,25 +500,19 @@ namespace Masuit.Tools.Hardware
             try
             {
                 IList<string> list = new List<string>();
-                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                using (mc)
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                using var moc = mc.GetInstances();
+                foreach (ManagementObject mo in moc)
                 {
-                    ManagementObjectCollection moc = mc.GetInstances();
-                    using (moc)
+                    if ((bool)mo["IPEnabled"])
                     {
-                        foreach (ManagementObject mo in moc)
-                        {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                var ar = (Array)(mo.Properties["IpAddress"].Value);
-                                var st = ar.GetValue(0).ToString();
-                                list.Add(st);
-                            }
-                        }
-
-                        return list;
+                        var ar = (Array)(mo.Properties["IpAddress"].Value);
+                        var st = ar.GetValue(0).ToString();
+                        list.Add(st);
                     }
                 }
+
+                return list;
             }
             catch (Exception)
             {
@@ -541,7 +530,7 @@ namespace Masuit.Tools.Hardware
         public static string GetLocalUsedIP()
         {
             string result = RunApp("route", "print", true);
-            Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
+            var m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)", RegexOptions.Compiled);
             if (m.Success)
             {
                 return m.Groups[2].Value;
@@ -549,12 +538,10 @@ namespace Masuit.Tools.Hardware
 
             try
             {
-                using (System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient())
-                {
-                    c.Connect("www.baidu.com", 80);
-                    var ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
-                    return ip;
-                }
+                using var c = new TcpClient();
+                c.Connect("www.baidu.com", 80);
+                var ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
+                return ip;
             }
             catch (Exception)
             {
@@ -591,24 +578,22 @@ namespace Masuit.Tools.Hardware
                 };
                 proc.Start();
 
-                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
+                using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
+                Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
+                //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
+                if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
                 {
-                    Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                    //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                    if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                    {
-                        //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
-                        proc.Kill();
-                    }
+                    //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
+                    proc.Kill();
+                }
 
-                    string txt = sr.ReadToEnd();
-                    sr.Close();
-                    if (recordLog)
-                    {
-                        Trace.WriteLine(txt);
-                    }
-                    return txt;
+                string txt = sr.ReadToEnd();
+                sr.Close();
+                if (recordLog)
+                {
+                    Trace.WriteLine(txt);
                 }
+                return txt;
             }
             catch (Exception ex)
             {

+ 2 - 4
Masuit.Tools.Core/Logging/LogManager.cs

@@ -440,10 +440,8 @@ namespace Masuit.Tools.Logging
                     File.CreateText(logPath).Close();
                 }
 
-                using (StreamWriter sw = File.AppendText(logPath))
-                {
-                    sw.Write(logContent);
-                }
+                using var sw = File.AppendText(logPath);
+                sw.Write(logContent);
             }
             catch (Exception)
             {

+ 1 - 1
Masuit.Tools.Core/Mapping/Core/MapperConfigurationCollectionContainer.cs

@@ -22,7 +22,7 @@ namespace Masuit.Tools.Mapping.Core
         /// <summary>
         /// mapper映射容器
         /// </summary>
-        public static MapperConfigurationCollectionContainer Instance => currentInstance ?? (currentInstance = new MapperConfigurationCollectionContainer());
+        public static MapperConfigurationCollectionContainer Instance => currentInstance ??= new MapperConfigurationCollectionContainer();
 
         /// <summary>
         /// count

+ 1 - 0
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -17,6 +17,7 @@ github:https://github.com/ldqk/Masuit.Tools</Description>
     <PackageLicenseUrl>https://github.com/ldqk/Masuit.Tools/blob/master/LICENSE</PackageLicenseUrl>
     <Product>Masuit.Tools.Core</Product>
     <PackageId>Masuit.Tools.Core</PackageId>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

+ 0 - 7
Masuit.Tools.Core/Masuit.Tools.Core.xml

@@ -4231,13 +4231,6 @@
             <returns></returns>
             <exception cref="T:System.Exception">操作失败。</exception>
         </member>
-        <member name="M:Masuit.Tools.Media.ImageUtilities.UploadImageAsync(System.IO.Stream)">
-            <summary>
-            上传图片到百度图床
-            </summary>
-            <param name="stream"></param>
-            <returns></returns>
-        </member>
         <member name="T:Masuit.Tools.Media.ThumbnailCutMode">
             <summary>
             图像裁剪模式

+ 221 - 325
Masuit.Tools.Core/Media/ImageUtilities.cs

@@ -4,8 +4,6 @@ using System.Drawing.Drawing2D;
 using System.Drawing.Imaging;
 using System.IO;
 using System.Linq;
-using System.Net.Http;
-using System.Net.Http.Headers;
 using System.Threading.Tasks;
 
 namespace Masuit.Tools.Media
@@ -295,13 +293,11 @@ namespace Masuit.Tools.Media
                 //文字水印
                 if (watermarkText != "")
                 {
-                    using (Graphics gWater = Graphics.FromImage(initImage))
-                    {
-                        Font fontWater = new Font("黑体", 10);
-                        Brush brushWater = new SolidBrush(Color.White);
-                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
-                        gWater.Dispose();
-                    }
+                    using var gWater = Graphics.FromImage(initImage);
+                    Font fontWater = new Font("黑体", 10);
+                    Brush brushWater = new SolidBrush(Color.White);
+                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
+                    gWater.Dispose();
                 }
 
                 //透明图片水印
@@ -309,38 +305,36 @@ namespace Masuit.Tools.Media
                 {
                     if (File.Exists(watermarkImage))
                     {
-                        using (Image wrImage = Image.FromFile(watermarkImage))
+                        using var wrImage = Image.FromFile(watermarkImage);
+                        //水印绘制条件:原始图片宽高均大于或等于水印图片
+                        if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
                         {
-                            //水印绘制条件:原始图片宽高均大于或等于水印图片
-                            if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
+                            Graphics gWater = Graphics.FromImage(initImage);
+
+                            //透明属性
+                            ImageAttributes imgAttributes = new ImageAttributes();
+                            ColorMap colorMap = new ColorMap();
+                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
+                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
+                            ColorMap[] remapTable = { colorMap };
+                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
+
+                            float[][] colorMatrixElements =
                             {
-                                Graphics gWater = Graphics.FromImage(initImage);
-
-                                //透明属性
-                                ImageAttributes imgAttributes = new ImageAttributes();
-                                ColorMap colorMap = new ColorMap();
-                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
-                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
-                                ColorMap[] remapTable = { colorMap };
-                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
-
-                                float[][] colorMatrixElements =
-                                {
-                                    new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
-                                    new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
-                                };
-
-                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
-                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
-                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
-
-                                gWater.Dispose();
-                            }
-                            wrImage.Dispose();
+                                new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
+                                new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
+                            };
+
+                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
+                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
+                            gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
+
+                            gWater.Dispose();
                         }
+                        wrImage.Dispose();
                     }
                 }
 
@@ -394,13 +388,11 @@ namespace Masuit.Tools.Media
                 //文字水印
                 if (watermarkText != "")
                 {
-                    using (Graphics gWater = Graphics.FromImage(newImage))
-                    {
-                        Font fontWater = new Font("宋体", 10);
-                        Brush brushWater = new SolidBrush(Color.White);
-                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
-                        gWater.Dispose();
-                    }
+                    using var gWater = Graphics.FromImage(newImage);
+                    Font fontWater = new Font("宋体", 10);
+                    Brush brushWater = new SolidBrush(Color.White);
+                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
+                    gWater.Dispose();
                 }
 
                 //透明图片水印
@@ -408,37 +400,35 @@ namespace Masuit.Tools.Media
                 {
                     if (File.Exists(watermarkImage))
                     {
-                        using (Image wrImage = Image.FromFile(watermarkImage))
+                        using Image wrImage = Image.FromFile(watermarkImage);
+                        //水印绘制条件:原始图片宽高均大于或等于水印图片
+                        if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
                         {
-                            //水印绘制条件:原始图片宽高均大于或等于水印图片
-                            if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
+                            Graphics gWater = Graphics.FromImage(newImage);
+
+                            //透明属性
+                            ImageAttributes imgAttributes = new ImageAttributes();
+                            ColorMap colorMap = new ColorMap();
+                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
+                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
+                            ColorMap[] remapTable = { colorMap };
+                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
+
+                            float[][] colorMatrixElements =
                             {
-                                Graphics gWater = Graphics.FromImage(newImage);
-
-                                //透明属性
-                                ImageAttributes imgAttributes = new ImageAttributes();
-                                ColorMap colorMap = new ColorMap();
-                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
-                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
-                                ColorMap[] remapTable = { colorMap };
-                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
-
-                                float[][] colorMatrixElements =
-                                {
-                                    new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
-                                    new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
-                                };
-
-                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
-                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
-                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
-                                gWater.Dispose();
-                            }
-                            wrImage.Dispose();
+                                new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
+                                new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
+                            };
+
+                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
+                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
+                            gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
+                            gWater.Dispose();
                         }
+                        wrImage.Dispose();
                     }
                 }
 
@@ -572,79 +562,69 @@ namespace Masuit.Tools.Media
                 return true;
             }
 
-            using (Image iSource = Image.FromFile(sFile))
+            using Image iSource = Image.FromFile(sFile);
+            ImageFormat tFormat = iSource.RawFormat;
+            int dHeight = iSource.Height;
+            int dWidth = iSource.Width;
+            int sW, sH;
+            //按比例缩放
+            Size temSize = new Size(iSource.Width, iSource.Height);
+            if (temSize.Width > dHeight || temSize.Width > dWidth)
             {
-                ImageFormat tFormat = iSource.RawFormat;
-                int dHeight = iSource.Height;
-                int dWidth = iSource.Width;
-                int sW, sH;
-                //按比例缩放
-                Size temSize = new Size(iSource.Width, iSource.Height);
-                if (temSize.Width > dHeight || temSize.Width > dWidth)
+                if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
                 {
-                    if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
-                    {
-                        sW = dWidth;
-                        sH = (dWidth * temSize.Height) / temSize.Width;
-                    }
-                    else
-                    {
-                        sH = dHeight;
-                        sW = (temSize.Width * dHeight) / temSize.Height;
-                    }
+                    sW = dWidth;
+                    sH = (dWidth * temSize.Height) / temSize.Width;
                 }
                 else
                 {
-                    sW = temSize.Width;
-                    sH = temSize.Height;
+                    sH = dHeight;
+                    sW = (temSize.Width * dHeight) / temSize.Height;
                 }
+            }
+            else
+            {
+                sW = temSize.Width;
+                sH = temSize.Height;
+            }
 
-                using (Bitmap bmp = new Bitmap(dWidth, dHeight))
+            using Bitmap bmp = new Bitmap(dWidth, dHeight);
+            using Graphics g = Graphics.FromImage(bmp);
+            g.Clear(Color.WhiteSmoke);
+            g.CompositingQuality = CompositingQuality.HighQuality;
+            g.SmoothingMode = SmoothingMode.HighQuality;
+            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
+
+            //以下代码为保存图片时,设置压缩质量
+            using EncoderParameters ep = new EncoderParameters();
+            long[] qy = new long[1];
+            qy[0] = flag;//设置压缩的比例1-100
+            using EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
+            ep.Param[0] = eParam;
+            try
+            {
+                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
+                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
+                if (jpegIcIinfo != null)
                 {
-                    using (Graphics g = Graphics.FromImage(bmp))
-                    {
-                        g.Clear(Color.WhiteSmoke);
-                        g.CompositingQuality = CompositingQuality.HighQuality;
-                        g.SmoothingMode = SmoothingMode.HighQuality;
-                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-                    }
-
-                    //以下代码为保存图片时,设置压缩质量
-                    using (EncoderParameters ep = new EncoderParameters())
+                    bmp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
+                    FileInfo fi = new FileInfo(dFile);
+                    if (fi.Length > 1024 * size)
                     {
-                        long[] qy = new long[1];
-                        qy[0] = flag;//设置压缩的比例1-100
-                        using (EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy))
-                        {
-                            ep.Param[0] = eParam;
-                            try
-                            {
-                                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
-                                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
-                                if (jpegIcIinfo != null)
-                                {
-                                    bmp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
-                                    FileInfo fi = new FileInfo(dFile);
-                                    if (fi.Length > 1024 * size)
-                                    {
-                                        flag = flag - 10;
-                                        CompressImage(sFile, dFile, flag, size, false);
-                                    }
-                                }
-                                else
-                                {
-                                    bmp.Save(dFile, tFormat);
-                                }
-                                return true;
-                            }
-                            catch
-                            {
-                                return false;
-                            }
-                        }
+                        flag = flag - 10;
+                        CompressImage(sFile, dFile, flag, size, false);
                     }
                 }
+                else
+                {
+                    bmp.Save(dFile, tFormat);
+                }
+                return true;
+            }
+            catch
+            {
+                return false;
             }
         }
 
@@ -666,78 +646,68 @@ namespace Masuit.Tools.Media
                 return true;
             }
 
-            using (Image iSource = Image.FromStream(src))
+            using Image iSource = Image.FromStream(src);
+            ImageFormat tFormat = iSource.RawFormat;
+            int dHeight = iSource.Height;
+            int dWidth = iSource.Width;
+            int sW, sH;
+            //按比例缩放
+            Size temSize = new Size(iSource.Width, iSource.Height);
+            if (temSize.Width > dHeight || temSize.Width > dWidth)
             {
-                ImageFormat tFormat = iSource.RawFormat;
-                int dHeight = iSource.Height;
-                int dWidth = iSource.Width;
-                int sW, sH;
-                //按比例缩放
-                Size temSize = new Size(iSource.Width, iSource.Height);
-                if (temSize.Width > dHeight || temSize.Width > dWidth)
+                if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
                 {
-                    if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
-                    {
-                        sW = dWidth;
-                        sH = (dWidth * temSize.Height) / temSize.Width;
-                    }
-                    else
-                    {
-                        sH = dHeight;
-                        sW = (temSize.Width * dHeight) / temSize.Height;
-                    }
+                    sW = dWidth;
+                    sH = (dWidth * temSize.Height) / temSize.Width;
                 }
                 else
                 {
-                    sW = temSize.Width;
-                    sH = temSize.Height;
+                    sH = dHeight;
+                    sW = (temSize.Width * dHeight) / temSize.Height;
                 }
+            }
+            else
+            {
+                sW = temSize.Width;
+                sH = temSize.Height;
+            }
 
-                using (Bitmap bmp = new Bitmap(dWidth, dHeight))
+            using Bitmap bmp = new Bitmap(dWidth, dHeight);
+            using Graphics g = Graphics.FromImage(bmp);
+            g.Clear(Color.WhiteSmoke);
+            g.CompositingQuality = CompositingQuality.HighQuality;
+            g.SmoothingMode = SmoothingMode.HighQuality;
+            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
+
+            //以下代码为保存图片时,设置压缩质量
+            using EncoderParameters ep = new EncoderParameters();
+            long[] qy = new long[1];
+            qy[0] = flag;//设置压缩的比例1-100
+            using EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
+            ep.Param[0] = eParam;
+            try
+            {
+                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
+                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
+                if (jpegIcIinfo != null)
                 {
-                    using (Graphics g = Graphics.FromImage(bmp))
-                    {
-                        g.Clear(Color.WhiteSmoke);
-                        g.CompositingQuality = CompositingQuality.HighQuality;
-                        g.SmoothingMode = SmoothingMode.HighQuality;
-                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-                    }
-
-                    //以下代码为保存图片时,设置压缩质量
-                    using (EncoderParameters ep = new EncoderParameters())
+                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
+                    if (dest.Length > 1024 * size)
                     {
-                        long[] qy = new long[1];
-                        qy[0] = flag;//设置压缩的比例1-100
-                        using (EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy))
-                        {
-                            ep.Param[0] = eParam;
-                            try
-                            {
-                                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
-                                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
-                                if (jpegIcIinfo != null)
-                                {
-                                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
-                                    if (dest.Length > 1024 * size)
-                                    {
-                                        flag = flag - 10;
-                                        CompressImage(src, dest, flag, size, false);
-                                    }
-                                }
-                                else
-                                {
-                                    bmp.Save(dest, tFormat);
-                                }
-                                return true;
-                            }
-                            catch
-                            {
-                                return false;
-                            }
-                        }
+                        flag = flag - 10;
+                        CompressImage(src, dest, flag, size, false);
                     }
                 }
+                else
+                {
+                    bmp.Save(dest, tFormat);
+                }
+                return true;
+            }
+            catch
+            {
+                return false;
             }
         }
 
@@ -934,18 +904,14 @@ namespace Masuit.Tools.Media
         {
             try
             {
-                using (Bitmap bap = new Bitmap(newW, newH))
+                using Bitmap bap = new Bitmap(newW, newH);
+                return await Task.Run(() =>
                 {
-                    return await Task.Run(() =>
-                    {
-                        using (Graphics g = Graphics.FromImage(bap))
-                        {
-                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                            g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
-                        }
-                        return bap;
-                    }).ConfigureAwait(false);
-                }
+                    using Graphics g = Graphics.FromImage(bap);
+                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                    g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
+                    return bap;
+                }).ConfigureAwait(false);
             }
             catch (Exception)
             {
@@ -965,21 +931,18 @@ namespace Masuit.Tools.Media
         /// <param name="height">原始图片的高度</param>
         public static Bitmap FilPic(this Bitmap mybm, int width, int height)
         {
-            using (Bitmap bm = new Bitmap(width, height)) //初始化一个记录滤色效果的图片对象
+            using var bm = new Bitmap(width, height);
+            for (var x = 0; x < width; x++)
             {
-                int x, y;
-                Color pixel;
-                for (x = 0; x < width; x++)
+                int y;
+                for (y = 0; y < height; y++)
                 {
-                    for (y = 0; y < height; y++)
-                    {
-                        pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
-                        bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -994,20 +957,20 @@ namespace Masuit.Tools.Media
         /// <param name="height">原始图片的高度</param>
         public static Bitmap RevPicLR(this Bitmap mybm, int width, int height)
         {
-            using (Bitmap bm = new Bitmap(width, height))
+            using var bm = new Bitmap(width, height);
+            //x,y是循环次数,z是用来记录像素点的x坐标的变化的
+            for (var y = height - 1; y >= 0; y--)
             {
-                int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-                for (y = height - 1; y >= 0; y--)
+                int x; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
+                int z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
+                for (x = width - 1, z = 0; x >= 0; x--)
                 {
-                    for (x = width - 1, z = 0; x >= 0; x--)
-                    {
-                        var pixel = mybm.GetPixel(x, y);
-                        bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -1022,21 +985,19 @@ namespace Masuit.Tools.Media
         /// <param name="height">原始图片的高度</param>
         public static Bitmap RevPicUD(this Bitmap mybm, int width, int height)
         {
-            Bitmap bm = new Bitmap(width, height);
-            using (bm)
+            using var bm = new Bitmap(width, height);
+            for (var x = 0; x < width; x++)
             {
-                int x, y, z;
-                for (x = 0; x < width; x++)
+                int y;
+                int z;
+                for (y = height - 1, z = 0; y >= 0; y--)
                 {
-                    for (y = height - 1, z = 0; y >= 0; y--)
-                    {
-                        var pixel = mybm.GetPixel(x, y);
-                        bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -1112,22 +1073,18 @@ namespace Masuit.Tools.Media
         /// <param name="height">图片的高度</param>
         public static Bitmap BWPic(this Bitmap mybm, int width, int height)
         {
-            Bitmap bm = new Bitmap(width, height);
-            using (bm)
+            using var bm = new Bitmap(width, height);
+            for (var x = 0; x < width; x++)
             {
-                int x, y; //x,y是循环次数
-                for (x = 0; x < width; x++)
+                for (var y = 0; y < height; y++)
                 {
-                    for (y = 0; y < height; y++)
-                    {
-                        var pixel = mybm.GetPixel(x, y);
-                        var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素值
-                        bm.SetPixel(x, y, Color.FromArgb(result, result, result));
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素值
+                    bm.SetPixel(x, y, Color.FromArgb(result, result, result));
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -1141,15 +1098,12 @@ namespace Masuit.Tools.Media
         /// <param name="pSavedPath">保存路径</param>
         public static void GetFrames(this Image gif, string pSavedPath)
         {
-            using (gif)
+            var fd = new FrameDimension(gif.FrameDimensionsList[0]);
+            int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
+            for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
             {
-                FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
-                int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
-                for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
-                {
-                    gif.SelectActiveFrame(fd, i);
-                    gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
-                }
+                gif.SelectActiveFrame(fd, i);
+                gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
             }
         }
 
@@ -1164,73 +1118,15 @@ namespace Masuit.Tools.Media
         /// <exception cref="Exception">操作失败。</exception>
         public static Bitmap SaveDataUriAsImageFile(this string source)
         {
-            string strbase64 = source.Substring(source.IndexOf(',') + 1);
-            strbase64 = strbase64.Trim('\0');
-            Bitmap bmp2;
+            string strbase64 = source.Substring(source.IndexOf(',') + 1).Trim('\0');
             byte[] arr = Convert.FromBase64String(strbase64);
-            using (var ms = new MemoryStream(arr))
-            {
-                var bmp = new Bitmap(ms);
-                //新建第二个bitmap类型的bmp2变量。
-                bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
-                //将第一个bmp拷贝到bmp2中
-                Graphics draw = Graphics.FromImage(bmp2);
-                using (draw)
-                {
-                    draw.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
-                }
-            }
+            using var ms = new MemoryStream(arr);
+            using var bmp = new Bitmap(ms);
+            //新建第二个bitmap类型的bmp2变量。
+            using var bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
+            using var draw = Graphics.FromImage(bmp2);
+            draw.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
             return bmp2;
         }
-
-        /// <summary>
-        /// 上传图片到百度图床
-        /// </summary>
-        /// <param name="stream"></param>
-        /// <returns></returns>
-        public static async Task<string> UploadImageAsync(Stream stream)
-        {
-            using (HttpClient httpClient = new HttpClient()
-            {
-                BaseAddress = new Uri("https://sm.ms"),
-            })
-            {
-                httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0"));
-                using (var bc = new StreamContent(stream))
-                {
-                    bc.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
-                    {
-                        FileName = "1.jpg",
-                        Name = "smfile"
-                    };
-                    bc.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
-                    using (var content = new MultipartFormDataContent { bc })
-                    {
-                        return await await httpClient.PostAsync("/api/upload", content).ContinueWith(async t =>
-                        {
-                            if (t.IsCanceled || t.IsFaulted)
-                            {
-                                Console.WriteLine("发送请求出错了" + t.Exception);
-                                return string.Empty;
-                            }
-                            var res = await t;
-                            if (res.IsSuccessStatusCode)
-                            {
-                                string s = await res.Content.ReadAsStringAsync();
-                                //var token = JObject.Parse(s);
-                                //if ((int)token["errno"] == 0)
-                                //{
-                                //    s = (string)token["data"]["imageUrl"];
-                                //    return s;
-                                //}
-                                //s = (string)token["errmsg"];
-                                return s;
-                            }
-                            return string.Empty;
-                        });
-                    }
-                }
-            }
-        }
-    } //end class
+    }
 }

+ 22 - 27
Masuit.Tools.Core/Models/Email.cs

@@ -83,20 +83,16 @@ namespace Masuit.Tools.Models
         /// <returns></returns>
         public void SendAsync(Action<string> completedCallback)
         {
-            using (SmtpClient smtpClient = GetSmtpClient)
-            {
-                using (MailMessage mailMessage = GetClient)
-                {
-                    if (smtpClient == null || mailMessage == null) return;
-                    Subject = Subject;
-                    Body = Body;
-                    //EnableSsl = false;
-                    //发送邮件回调方法
-                    actionSendCompletedCallback = completedCallback;
-                    smtpClient.SendCompleted += SendCompletedCallback;
-                    smtpClient.SendAsync(mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-                }
-            }
+            using var smtpClient = GetSmtpClient;
+            using var mailMessage = GetClient;
+            if (smtpClient == null || mailMessage == null) return;
+            Subject = Subject;
+            Body = Body;
+            //EnableSsl = false;
+            //发送邮件回调方法
+            actionSendCompletedCallback = completedCallback;
+            smtpClient.SendCompleted += SendCompletedCallback;
+            smtpClient.SendAsync(mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
         }
 
         /// <summary>
@@ -104,17 +100,13 @@ namespace Masuit.Tools.Models
         /// </summary>
         public void Send()
         {
-            using (SmtpClient smtpClient = GetSmtpClient)
-            {
-                using (MailMessage mailMessage = GetClient)
-                {
-                    if (smtpClient == null || mailMessage == null) return;
-                    Subject = Subject;
-                    Body = Body;
-                    //EnableSsl = false;
-                    smtpClient.Send(mailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-                }
-            }
+            using SmtpClient smtpClient = GetSmtpClient;
+            using MailMessage mailMessage = GetClient;
+            if (smtpClient == null || mailMessage == null) return;
+            Subject = Subject;
+            Body = Body;
+            //EnableSsl = false;
+            smtpClient.Send(mailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
         }
 
         /// <summary>
@@ -128,17 +120,20 @@ namespace Masuit.Tools.Models
             //写入日志
             //return;
             if (actionSendCompletedCallback == null) return;
-            string message = string.Empty;
+            string message;
             if (e.Cancelled)
             {
                 message = "异步操作取消";
             }
             else if (e.Error != null)
             {
-                message = (string.Format("UserState:{0},Message:{1}", (string)e.UserState, e.Error.ToString()));
+                message = ($"UserState:{(string)e.UserState},Message:{e.Error}");
             }
             else
+            {
                 message = (string)e.UserState;
+            }
+
             //执行回调方法
             actionSendCompletedCallback(message);
         }

+ 136 - 194
Masuit.Tools.Core/Net/FtpClient.cs

@@ -83,55 +83,45 @@ namespace Masuit.Tools.Net
         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
         public void Download(string remoteFileName, string localFileName, bool ifCredential = false, Action<int, int> updateProgress = null)
         {
-            using (FileStream outputStream = new FileStream(localFileName, FileMode.Create))
+            using FileStream outputStream = new FileStream(localFileName, FileMode.Create);
+            if (FtpServer == null || FtpServer.Trim().Length == 0)
             {
-                if (FtpServer == null || FtpServer.Trim().Length == 0)
-                {
-                    throw new Exception("ftp下载目标服务器地址未设置!");
-                }
+                throw new Exception("ftp下载目标服务器地址未设置!");
+            }
 
-                Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
-                var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
-                ftpsize.UseBinary = true;
-                var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-                reqFtp.UseBinary = true;
-                reqFtp.KeepAlive = false;
-                if (ifCredential) //使用用户身份认证
-                {
-                    ftpsize.Credentials = new NetworkCredential(Username, Password);
-                    reqFtp.Credentials = new NetworkCredential(Username, Password);
-                }
+            Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
+            var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
+            ftpsize.UseBinary = true;
+            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
+            reqFtp.UseBinary = true;
+            reqFtp.KeepAlive = false;
+            if (ifCredential) //使用用户身份认证
+            {
+                ftpsize.Credentials = new NetworkCredential(Username, Password);
+                reqFtp.Credentials = new NetworkCredential(Username, Password);
+            }
 
-                ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
-                using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
+            ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
+            using var re = (FtpWebResponse)ftpsize.GetResponse();
+            long totalBytes = re.ContentLength;
+            reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var ftpStream = response.GetResponseStream();
+            //更新进度 
+            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
+            long totalDownloadedByte = 0;
+            int bufferSize = 1024 * 1024;
+            byte[] buffer = new byte[bufferSize];
+            if (ftpStream != null)
+            {
+                var readCount = ftpStream.Read(buffer, 0, bufferSize);
+                while (readCount > 0)
                 {
-                    long totalBytes = re.ContentLength;
-                    reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
-                    var response = (FtpWebResponse)reqFtp.GetResponse();
-                    using (response)
-                    {
-                        var ftpStream = response.GetResponseStream();
-                        //更新进度 
-                        using (ftpStream)
-                        {
-                            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
-                            long totalDownloadedByte = 0;
-                            int bufferSize = 1024 * 1024;
-                            byte[] buffer = new byte[bufferSize];
-                            if (ftpStream != null)
-                            {
-                                var readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                while (readCount > 0)
-                                {
-                                    totalDownloadedByte = readCount + totalDownloadedByte;
-                                    outputStream.Write(buffer, 0, readCount);
-                                    //更新进度 
-                                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
-                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                }
-                            }
-                        }
-                    }
+                    totalDownloadedByte = readCount + totalDownloadedByte;
+                    outputStream.Write(buffer, 0, readCount);
+                    //更新进度 
+                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
+                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                 }
             }
         }
@@ -146,54 +136,46 @@ namespace Masuit.Tools.Net
         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
         public void BrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
         {
-            using (FileStream outputStream = new FileStream(localFileName, FileMode.Append))
+            using var outputStream = new FileStream(localFileName, FileMode.Append);
+            if (FtpServer == null || FtpServer.Trim().Length == 0)
             {
-                if (FtpServer == null || FtpServer.Trim().Length == 0)
-                {
-                    throw new Exception("ftp下载目标服务器地址未设置!");
-                }
+                throw new Exception("ftp下载目标服务器地址未设置!");
+            }
 
-                Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
-                var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
-                ftpsize.UseBinary = true;
-                ftpsize.ContentOffset = size;
-                var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-                reqFtp.UseBinary = true;
-                reqFtp.KeepAlive = false;
-                reqFtp.ContentOffset = size;
-                if (ifCredential) //使用用户身份认证
-                {
-                    ftpsize.Credentials = new NetworkCredential(Username, Password);
-                    reqFtp.Credentials = new NetworkCredential(Username, Password);
-                }
+            Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
+            var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
+            ftpsize.UseBinary = true;
+            ftpsize.ContentOffset = size;
+            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
+            reqFtp.UseBinary = true;
+            reqFtp.KeepAlive = false;
+            reqFtp.ContentOffset = size;
+            if (ifCredential) //使用用户身份认证
+            {
+                ftpsize.Credentials = new NetworkCredential(Username, Password);
+                reqFtp.Credentials = new NetworkCredential(Username, Password);
+            }
 
-                ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
-                using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
+            ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
+            using FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
+            var totalBytes = re.ContentLength;
+            reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var ftpStream = response.GetResponseStream();
+            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
+            long totalDownloadedByte = 0;
+            int bufferSize = 1024 * 1024;
+            byte[] buffer = new byte[bufferSize];
+            if (ftpStream != null)
+            {
+                var readCount = ftpStream.Read(buffer, 0, bufferSize);
+                while (readCount > 0)
                 {
-                    var totalBytes = re.ContentLength;
-                    reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
-                    using (var response = (FtpWebResponse)reqFtp.GetResponse())
-                    {
-                        using (var ftpStream = response.GetResponseStream())
-                        {
-                            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
-                            long totalDownloadedByte = 0;
-                            int bufferSize = 1024 * 1024;
-                            byte[] buffer = new byte[bufferSize];
-                            if (ftpStream != null)
-                            {
-                                var readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                while (readCount > 0)
-                                {
-                                    totalDownloadedByte = readCount + totalDownloadedByte;
-                                    outputStream.Write(buffer, 0, readCount);
-                                    //更新进度 
-                                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
-                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                }
-                            }
-                        }
-                    }
+                    totalDownloadedByte = readCount + totalDownloadedByte;
+                    outputStream.Write(buffer, 0, readCount);
+                    //更新进度 
+                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
+                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                 }
             }
         }
@@ -213,10 +195,8 @@ namespace Masuit.Tools.Net
                 long size = 0;
                 if (File.Exists(localFileName))
                 {
-                    using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
-                    {
-                        size = outputStream.Length;
-                    }
+                    using var outputStream = new FileStream(localFileName, FileMode.Open);
+                    size = outputStream.Length;
                 }
 
                 BrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
@@ -252,24 +232,20 @@ namespace Masuit.Tools.Net
             reqFtp.ContentLength = finfo.Length; //为request指定上传文件的大小
             int buffLength = 1024 * 1024;
             byte[] buff = new byte[buffLength];
-            using (var fs = finfo.OpenRead())
+            using var fs = finfo.OpenRead();
+            using var stream = reqFtp.GetRequestStream();
+            var contentLen = fs.Read(buff, 0, buffLength);
+            int allbye = (int)finfo.Length;
+            //更新进度 
+            updateProgress?.Invoke(allbye, 0); //更新进度条 
+            int startbye = 0;
+            while (contentLen != 0)
             {
-                using (var stream = reqFtp.GetRequestStream())
-                {
-                    var contentLen = fs.Read(buff, 0, buffLength);
-                    int allbye = (int)finfo.Length;
-                    //更新进度 
-                    updateProgress?.Invoke(allbye, 0); //更新进度条 
-                    int startbye = 0;
-                    while (contentLen != 0)
-                    {
-                        startbye = contentLen + startbye;
-                        stream.Write(buff, 0, contentLen);
-                        //更新进度 
-                        updateProgress?.Invoke(allbye, startbye); //更新进度条 
-                        contentLen = fs.Read(buff, 0, buffLength);
-                    }
-                }
+                startbye = contentLen + startbye;
+                stream.Write(buff, 0, contentLen);
+                //更新进度 
+                updateProgress?.Invoke(allbye, startbye); //更新进度条 
+                contentLen = fs.Read(buff, 0, buffLength);
             }
         }
 
@@ -336,24 +312,20 @@ namespace Masuit.Tools.Net
             int buffLength = 1024 * 1024; // 缓冲大小设置为2kb 
             byte[] buff = new byte[buffLength];
             // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
-            using (FileStream fs = fileInf.OpenRead())
+            using FileStream fs = fileInf.OpenRead();
+            using var strm = reqFtp.GetRequestStream();
+            // 把上传的文件写入流 
+            fs.Seek(startfilesize, 0);
+            int contentLen = fs.Read(buff, 0, buffLength);
+            // 流内容没有结束 
+            while (contentLen != 0)
             {
-                using (var strm = reqFtp.GetRequestStream())
-                {
-                    // 把上传的文件写入流 
-                    fs.Seek(startfilesize, 0);
-                    int contentLen = fs.Read(buff, 0, buffLength);
-                    // 流内容没有结束 
-                    while (contentLen != 0)
-                    {
-                        // 把内容从file stream 写入 upload stream 
-                        strm.Write(buff, 0, contentLen);
-                        contentLen = fs.Read(buff, 0, buffLength);
-                        startbye += contentLen;
-                        //更新进度 
-                        updateProgress?.Invoke((int)allbye, (int)startbye); //更新进度条 
-                    }
-                }
+                // 把内容从file stream 写入 upload stream 
+                strm.Write(buff, 0, contentLen);
+                contentLen = fs.Read(buff, 0, buffLength);
+                startbye += contentLen;
+                //更新进度 
+                updateProgress?.Invoke((int)allbye, (int)startbye); //更新进度条 
             }
 
             return true;
@@ -406,7 +378,7 @@ namespace Masuit.Tools.Net
                 reqFtp.UseBinary = true;
                 reqFtp.Credentials = new NetworkCredential(Username, Password); //用户,密码
                 reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
-                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
+                var response = (FtpWebResponse)reqFtp.GetResponse();
                 var filesize = response.ContentLength;
                 return filesize;
             }
@@ -426,21 +398,17 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public List<string> GetFilesDetails(string relativePath = "")
         {
-            List<string> result = new List<string>();
+            var result = new List<string>();
             var ftp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, relativePath).Replace("\\", "/")));
             ftp.Credentials = new NetworkCredential(Username, Password);
             ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
-            using (WebResponse response = ftp.GetResponse())
+            using var response = ftp.GetResponse();
+            using var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
+            string line = reader.ReadLine();
+            while (line != null)
             {
-                using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8))
-                {
-                    string line = reader.ReadLine();
-                    while (line != null)
-                    {
-                        result.Add(line);
-                        line = reader.ReadLine();
-                    }
-                }
+                result.Add(line);
+                line = reader.ReadLine();
             }
 
             return result;
@@ -457,29 +425,25 @@ namespace Masuit.Tools.Net
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
             reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
-            using (WebResponse response = reqFtp.GetResponse())
+            using var response = reqFtp.GetResponse();
+            using var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
+            string line = reader.ReadLine();
+            while (line != null)
             {
-                using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8))
+                if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
                 {
-                    string line = reader.ReadLine();
-                    while (line != null)
+                    string temp = mask.Substring(0, mask.IndexOf("*", StringComparison.Ordinal));
+                    if (line.Substring(0, temp.Length) == temp)
                     {
-                        if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
-                        {
-                            string temp = mask.Substring(0, mask.IndexOf("*", StringComparison.Ordinal));
-                            if (line.Substring(0, temp.Length) == temp)
-                            {
-                                result.Add(line);
-                            }
-                        }
-                        else
-                        {
-                            result.Add(line);
-                        }
-
-                        line = reader.ReadLine();
+                        result.Add(line);
                     }
                 }
+                else
+                {
+                    result.Add(line);
+                }
+
+                line = reader.ReadLine();
             }
 
             return result;
@@ -536,16 +500,10 @@ namespace Masuit.Tools.Net
             reqFtp.KeepAlive = false;
             reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
 
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (Stream datastream = response.GetResponseStream())
-                {
-                    using (StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException()))
-                    {
-                        sr.ReadToEnd();
-                    }
-                }
-            }
+            using FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
+            using Stream datastream = response.GetResponseStream();
+            using StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException());
+            sr.ReadToEnd();
         }
 
         /// <summary>
@@ -559,16 +517,10 @@ namespace Masuit.Tools.Net
             reqFtp.Credentials = new NetworkCredential(Username, Password);
             reqFtp.KeepAlive = false;
             reqFtp.Method = WebRequestMethods.Ftp.RemoveDirectory;
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (Stream datastream = response.GetResponseStream())
-                {
-                    using (StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException()))
-                    {
-                        sr.ReadToEnd();
-                    }
-                }
-            }
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var datastream = response.GetResponseStream();
+            using var sr = new StreamReader(datastream ?? throw new InvalidOperationException());
+            sr.ReadToEnd();
         }
 
         #endregion
@@ -586,11 +538,9 @@ namespace Masuit.Tools.Net
             reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                var fileSize = response.ContentLength;
-                return fileSize;
-            }
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            var fileSize = response.ContentLength;
+            return fileSize;
         }
 
         /// <summary>
@@ -648,12 +598,8 @@ namespace Masuit.Tools.Net
             reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (response.GetResponseStream())
-                {
-                }
-            }
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var _ = response.GetResponseStream();
         }
 
         /// <summary>
@@ -669,12 +615,8 @@ namespace Masuit.Tools.Net
             reqFtp.RenameTo = newFilename;
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (response.GetResponseStream())
-                {
-                }
-            }
+            using FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
+            using var _ = response.GetResponseStream();
         }
 
         /// <summary>

+ 24 - 33
Masuit.Tools.Core/Net/MultiThreadDownloader.cs

@@ -233,31 +233,27 @@ namespace Masuit.Tools.Net
         void MergeParts()
         {
             List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
-            using (var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
+            using var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite);
+            long totalBytesWritten = 0;
+            int mergeProgress = 0;
+            foreach (var item in mergeOrderedList)
             {
-                long totalBytesWritten = 0;
-                int mergeProgress = 0;
-                foreach (var item in mergeOrderedList)
+                using var pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read);
+                byte[] buffer = new byte[4096];
+                int read;
+                while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
                 {
-                    using (FileStream pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read))
+                    fs.Write(buffer, 0, read);
+                    totalBytesWritten += read;
+                    int temp = (int)(totalBytesWritten * 1d / Size * 100);
+                    if (temp != mergeProgress && FileMergeProgressChanged != null)
                     {
-                        byte[] buffer = new byte[4096];
-                        int read;
-                        while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
-                        {
-                            fs.Write(buffer, 0, read);
-                            totalBytesWritten += read;
-                            int temp = (int)(totalBytesWritten * 1d / Size * 100);
-                            if (temp != mergeProgress && FileMergeProgressChanged != null)
-                            {
-                                mergeProgress = temp;
-                                _aop.Post(state => FileMergeProgressChanged(this, temp), null);
-                            }
-                        }
+                        mergeProgress = temp;
+                        _aop.Post(state => FileMergeProgressChanged(this, temp), null);
                     }
-
-                    File.Delete(item.FullPath);
                 }
+
+                File.Delete(item.FullPath);
             }
         }
 
@@ -338,22 +334,17 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static long GetContentLength(string url, ref bool rangeAllowed, ref string redirectedUrl)
         {
-            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
+            var req = WebRequest.Create(url) as HttpWebRequest;
             req.UserAgent = "Mozilla/4.0 (compatible; MSIE 11.0; Windows NT 6.2; .NET CLR 1.0.3705;)";
             req.ServicePoint.ConnectionLimit = 4;
-            long ctl;
-            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
+            using var resp = req.GetResponse() as HttpWebResponse;
+            redirectedUrl = resp.ResponseUri.OriginalString;
+            var ctl = resp.ContentLength;
+            rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
             {
-                redirectedUrl = resp.ResponseUri.OriginalString;
-                ctl = resp.ContentLength;
-                rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
-                {
-                    HeaderName = v,
-                    HeaderValue = resp.Headers[i]
-                }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
-                resp.Close();
-            }
-
+                HeaderName = v,
+                HeaderValue = resp.Headers[i]
+            }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
             req.Abort();
             return ctl;
         }

+ 93 - 84
Masuit.Tools.Core/Net/SocketClient.cs

@@ -232,7 +232,7 @@ namespace Masuit.Tools.Net
             }
 
             stream.Seek(0, SeekOrigin.Begin); //必须要这个 或者stream.Position = 0;
-            T t = (T) format.Deserialize(stream);
+            T t = (T)format.Deserialize(stream);
             stream.Close();
             return t;
         }
@@ -248,51 +248,57 @@ namespace Masuit.Tools.Net
         /// <param name="progress">处理过程</param>
         public static bool ReceiveFile(this Socket socket, string path, string filename, long size, Action<int> progress)
         {
+            if (!Directory.Exists(path))
+            {
+                return false;
+            }
+
+            //主要是防止有重名文件
+            string savepath = GetPath(path, filename); //得到文件路径
+            //缓冲区
+            byte[] file = new byte[m_maxpacket];
+            int receivedata = m_maxpacket; //每次要接收的长度
+            long offset = 0; //循环接收的总长度
+            long lastdata = size; //剩余多少还没接收
+            int mark = 0;
+            using var fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write);
+            if (size <= 0)
+            {
+                return false;
+            }
+
             bool ret = false;
-            if (Directory.Exists(path))
+            while (true)
             {
-                //主要是防止有重名文件
-                string savepath = GetPath(path, filename); //得到文件路径
-                //缓冲区
-                byte[] file = new byte[m_maxpacket];
-                int receivedata = m_maxpacket; //每次要接收的长度
-                long offset = 0; //循环接收的总长度
-                long lastdata = size; //剩余多少还没接收
-                int mark = 0;
-                using (FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write))
+                if (lastdata < receivedata)
                 {
-                    if (size > 0)
-                        while (true)
-                        {
-                            if (lastdata < receivedata)
-                                receivedata = Convert.ToInt32(lastdata);
-                            var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
-                            if (count > 0)
-                            {
-                                fs.Write(file, 0, count);
-                                offset += count;
-                                lastdata -= count;
-                                mark = 0;
-                            }
-                            else
-                            {
-                                mark++; //连续5次接收为0字节 则跳出循环
-                                if (mark == 10)
-                                    break;
-                            }
-
-                            //接收进度
-                            if (progress != null)
-                                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
-                            //接收完毕
-                            if (offset == size)
-                            {
-                                ret = true;
-                                break;
-                            }
-                        }
-
-                    fs.Close();
+                    receivedata = Convert.ToInt32(lastdata);
+                }
+
+                var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
+                if (count > 0)
+                {
+                    fs.Write(file, 0, count);
+                    offset += count;
+                    lastdata -= count;
+                    mark = 0;
+                }
+                else
+                {
+                    mark++; //连续5次接收为0字节 则跳出循环
+                    if (mark == 10)
+                    {
+                        break;
+                    }
+                }
+
+                //接收进度
+                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
+                //接收完毕
+                if (offset == size)
+                {
+                    ret = true;
+                    break;
                 }
             }
 
@@ -467,50 +473,55 @@ namespace Masuit.Tools.Net
         /// <returns>处理结果</returns>
         public static bool SendFile(this Socket socket, string path, bool issend, Action<int> progress)
         {
-            bool ret = false;
-            if (File.Exists(path))
+            if (!File.Exists(path))
+            {
+                return false;
+            }
+
+            var fileinfo = new FileInfo(path);
+            string filename = fileinfo.Name;
+            long length = fileinfo.Length;
+            //发送文件信息
+            if (issend)
             {
-                FileInfo fileinfo = new FileInfo(path);
-                string filename = fileinfo.Name;
-                long length = fileinfo.Length;
-                //发送文件信息
-                if (issend)
-                    SendVarData(socket, filename + "|" + length);
-                //发送文件
-                long offset = 0;
-                byte[] b = new byte[m_maxpacket];
-                int mark = 0;
-                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
+                SendVarData(socket, filename + "|" + length);
+            }
+
+            //发送文件
+            long offset = 0;
+            byte[] b = new byte[m_maxpacket];
+            int mark = 0;
+            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
+            int senddata = b.Length;
+            //循环读取发送
+            while (true)
+            {
+                int count = fs.Read(b, 0, senddata);
+                if (count > 0)
+                {
+                    socket.Send(b, 0, count, SocketFlags.None);
+                    offset += count;
+                    mark = 0;
+                }
+                else
                 {
-                    int senddata = b.Length;
-                    long i = length;
-                    //循环读取发送
-                    while (true)
+                    mark++;
+                    if (mark == 10)
                     {
-                        int count = fs.Read(b, 0, senddata);
-                        if (count > 0)
-                        {
-                            socket.Send(b, 0, count, SocketFlags.None);
-                            offset += count;
-                            mark = 0;
-                        }
-                        else
-                        {
-                            mark++;
-                            if (mark == 10)
-                                break;
-                        }
-
-                        if (progress != null)
-                            progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
-                        if (offset == length)
-                            break;
-                        Thread.Sleep(50); //设置等待时间,以免粘包
+                        break;
                     }
                 }
+
+                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
+                if (offset == length)
+                {
+                    return true;
+                }
+
+                Thread.Sleep(50); //设置等待时间,以免粘包
             }
 
-            return ret;
+            return false;
         }
 
         /// <summary>
@@ -539,11 +550,9 @@ namespace Masuit.Tools.Net
         private static byte[] SerializeObject(object obj)
         {
             IFormatter format = new BinaryFormatter();
-            MemoryStream stream = new MemoryStream();
+            using var stream = new MemoryStream();
             format.Serialize(stream, obj);
-            byte[] ret = stream.ToArray();
-            stream.Close();
-            return ret;
+            return stream.ToArray();
         }
 
         private static string GetSendPacketLengthStr(int size)

+ 77 - 77
Masuit.Tools.Core/Net/WebExtension.cs

@@ -46,79 +46,80 @@ namespace Masuit.Tools.Core.Net
         /// <returns></returns>
         public static async Task<PhysicsAddress> GetPhysicsAddressInfo(this string ip)
         {
-            ip.MatchInetAddress(out var isIpAddress);
-            if (isIpAddress)
+            if (!ip.MatchInetAddress())
+            {
+                return null;
+            }
+
+            string ak = CoreConfig.Configuration["BaiduAK"];
+            if (string.IsNullOrEmpty(ak))
             {
-                string ak = CoreConfig.Configuration["BaiduAK"];
-                if (string.IsNullOrEmpty(ak))
+                throw new Exception("未配置BaiduAK,请先在您的应用程序appsettings.json中下添加BaiduAK配置节(注意大小写)");
+            }
+
+            using var client = new HttpClient() { BaseAddress = new Uri("http://api.map.baidu.com") };
+            client.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
+            var task = client.GetAsync($"/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
+            {
+                if (t.IsFaulted || t.IsCanceled)
                 {
-                    throw new Exception("未配置BaiduAK,请先在您的应用程序appsettings.json中下添加BaiduAK配置节(注意大小写)");
+                    return null;
                 }
-                using (HttpClient client = new HttpClient() { BaseAddress = new Uri("http://api.map.baidu.com") })
+                var res = await t;
+                if (!res.IsSuccessStatusCode)
                 {
-                    client.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
-                    var task = client.GetAsync($"/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
+                    return null;
+                }
+
+                var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
+                if (ipAddress.Status == 0)
+                {
+                    var point = ipAddress.AddressInfo.LatiLongitude;
+                    var result = client.GetStringAsync($"/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
+                    var address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
+                    if (address.Status == 0)
+                    {
+                        return address;
+                    }
+                }
+                else
+                {
+                    using var client2 = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") };
+                    return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
                     {
-                        if (t.IsFaulted || t.IsCanceled)
+                        if (tt.IsFaulted || tt.IsCanceled)
                         {
                             return null;
                         }
-                        var res = await t;
-                        if (res.IsSuccessStatusCode)
+                        var result = await tt;
+                        if (!result.IsSuccessStatusCode)
                         {
-                            var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
-                            if (ipAddress.Status == 0)
-                            {
-                                LatiLongitude point = ipAddress.AddressInfo.LatiLongitude;
-                                string result = client.GetStringAsync($"/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
-                                PhysicsAddress address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
-                                if (address.Status == 0)
-                                {
-                                    return address;
-                                }
-                            }
-                            else
+                            return null;
+                        }
+
+                        var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
+                        if (taobaoIp.Code == 0)
+                        {
+                            return new PhysicsAddress()
                             {
-                                using (var client2 = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") })
+                                Status = 0,
+                                AddressResult = new AddressResult()
                                 {
-                                    return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
+                                    FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
+                                    AddressComponent = new AddressComponent()
                                     {
-                                        if (tt.IsFaulted || tt.IsCanceled)
-                                        {
-                                            return null;
-                                        }
-                                        var result = await tt;
-                                        if (result.IsSuccessStatusCode)
-                                        {
-                                            TaobaoIP taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                                            if (taobaoIp.Code == 0)
-                                            {
-                                                return new PhysicsAddress()
-                                                {
-                                                    Status = 0,
-                                                    AddressResult = new AddressResult()
-                                                    {
-                                                        FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
-                                                        AddressComponent = new AddressComponent()
-                                                        {
-                                                            Province = taobaoIp.IpData.Region
-                                                        },
-                                                        Pois = new List<Pois>()
-                                                    }
-                                                };
-                                            }
-                                        }
-                                        return null;
-                                    });
+                                        Province = taobaoIp.IpData.Region
+                                    },
+                                    Pois = new List<Pois>()
                                 }
-                            }
+                            };
                         }
                         return null;
                     });
-                    return await await task;
                 }
-            }
-            return null;
+                return null;
+            });
+            return await await task;
         }
 
         /// <summary>
@@ -128,31 +129,30 @@ namespace Masuit.Tools.Core.Net
         /// <returns></returns>
         public static string GetISP(this string ip)
         {
-            if (ip.MatchInetAddress())
+            if (!ip.MatchInetAddress())
             {
-                using (var client = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") })
+                return $"{ip}不是一个合法的IP";
+            }
+
+            using var client = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") };
+            var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
+            {
+                if (t.IsFaulted)
                 {
-                    var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
+                    return $"未能找到{ip}的ISP信息";
+                }
+                var result = await t;
+                if (result.IsSuccessStatusCode)
+                {
+                    var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
+                    if (taobaoIp.Code == 0)
                     {
-                        if (t.IsFaulted)
-                        {
-                            return $"未能找到{ip}的ISP信息";
-                        }
-                        var result = await t;
-                        if (result.IsSuccessStatusCode)
-                        {
-                            TaobaoIP taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                            if (taobaoIp.Code == 0)
-                            {
-                                return taobaoIp.IpData.Isp;
-                            }
-                        }
-                        return $"未能找到{ip}的ISP信息";
-                    });
-                    return task.Result.Result;
+                        return taobaoIp.IpData.Isp;
+                    }
                 }
-            }
-            return $"{ip}不是一个合法的IP";
+                return $"未能找到{ip}的ISP信息";
+            });
+            return task.Result.Result;
         }
 
         #endregion

+ 116 - 174
Masuit.Tools.Core/Security/Encrypt.cs

@@ -103,23 +103,18 @@ namespace Masuit.Tools.Security
                 0xEF
             };
             var byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
-            using (fin)
+            using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
+            fout.SetLength(0);
+            byte[] bin = new byte[100];
+            long rdlen = 0;
+            long totlen = fin.Length;
+            DES des = new DESCryptoServiceProvider();
+            var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
+            while (rdlen < totlen)
             {
-                using (FileStream fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write))
-                {
-                    fout.SetLength(0);
-                    byte[] bin = new byte[100];
-                    long rdlen = 0;
-                    long totlen = fin.Length;
-                    DES des = new DESCryptoServiceProvider();
-                    var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
-                    while (rdlen < totlen)
-                    {
-                        var len = fin.Read(bin, 0, 100);
-                        encStream.Write(bin, 0, len);
-                        rdlen += len;
-                    }
-                }
+                var len = fin.Read(bin, 0, 100);
+                encStream.Write(bin, 0, len);
+                rdlen += len;
             }
         }
 
@@ -143,23 +138,18 @@ namespace Masuit.Tools.Security
                 0xEF
             };
             var byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
-            using (fin)
+            using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
+            fout.SetLength(0);
+            byte[] bin = new byte[100];
+            long rdlen = 0;
+            long totlen = fin.Length;
+            DES des = new DESCryptoServiceProvider();
+            var encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
+            while (rdlen < totlen)
             {
-                using (FileStream fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write))
-                {
-                    fout.SetLength(0);
-                    byte[] bin = new byte[100];
-                    long rdlen = 0;
-                    long totlen = fin.Length;
-                    DES des = new DESCryptoServiceProvider();
-                    CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
-                    while (rdlen < totlen)
-                    {
-                        var len = fin.Read(bin, 0, 100);
-                        encStream.Write(bin, 0, len);
-                        rdlen += len;
-                    }
-                }
+                var len = fin.Read(bin, 0, 100);
+                encStream.Write(bin, 0, len);
+                rdlen += len;
             }
         }
 
@@ -420,7 +410,7 @@ namespace Masuit.Tools.Security
                 Key = Encoding.UTF8.GetBytes(decryptKey),
                 IV = Keys
             };
-            ICryptoTransform decrypto = rijndaelProvider.CreateDecryptor();
+            var decrypto = rijndaelProvider.CreateDecryptor();
             return new CryptoStream(fs, decrypto, CryptoStreamMode.Read);
         }
 
@@ -431,13 +421,11 @@ namespace Masuit.Tools.Security
         /// <param name="outputPath">输出文件路径</param>
         public static void AESEncryptFile(this FileStream input, string outputPath)
         {
-            using (FileStream fren = new FileStream(outputPath, FileMode.Create))
-            {
-                CryptoStream enfr = AESEncryptStrream(fren, Default_AES_Key);
-                byte[] bytearrayinput = new byte[input.Length];
-                input.Read(bytearrayinput, 0, bytearrayinput.Length);
-                enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
-            }
+            using var fren = new FileStream(outputPath, FileMode.Create);
+            var enfr = AESEncryptStrream(fren, Default_AES_Key);
+            byte[] bytearrayinput = new byte[input.Length];
+            input.Read(bytearrayinput, 0, bytearrayinput.Length);
+            enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
         }
 
         /// <summary>
@@ -1213,26 +1201,17 @@ namespace Masuit.Tools.Security
         /// <param name="toEncryptText">要加密的文本数据</param>
         /// <param name="filePath">要保存的文件</param>
         /// <returns>是否加密成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath)
+        public static void EncryptToFile(this string toEncryptText, string filePath)
         {
-            bool r;
-            using (var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true))
-            {
-                using (var encryptor = _rc2Csp.CreateEncryptor(_key, _iv))
-                {
-                    var msEncrypt = new MemoryStream();
-                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = _textConverter.GetBytes(toEncryptText);
-                        csEncrypt.Write(tmp, 0, tmp.Length);
-                        csEncrypt.FlushFinalBlock();
-                    }
-                    var encrypted = msEncrypt.ToArray();
-                    tmpFileStream.Write(encrypted, 0, encrypted.Length);
-                    r = true;
-                }
-            }
-            return r;
+            using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
+            using var encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
+            var msEncrypt = new MemoryStream();
+            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
+            var tmp = _textConverter.GetBytes(toEncryptText);
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            csEncrypt.FlushFinalBlock();
+            var encrypted = msEncrypt.ToArray();
+            tmpFileStream.Write(encrypted, 0, encrypted.Length);
         }
 
         #endregion
@@ -1246,26 +1225,17 @@ namespace Masuit.Tools.Security
         /// <returns>解密后的文本</returns>
         public static string DecryptFromFile(this string filePath)
         {
-            using (var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
-            {
-                using (var decryptor = _rc2Csp.CreateDecryptor(_key, _iv))
-                {
-                    var msDecrypt = new MemoryStream();
-                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = new byte[tmpFileStream.Length];
-                        tmpFileStream.Read(tmp, 0, tmp.Length);
-                        csDecrypt.Write(tmp, 0, tmp.Length);
-                        csDecrypt.FlushFinalBlock();
-                    }
-
-                    var decrypted = msDecrypt.ToArray();
-                    var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-                    return r;
-                }
-
-            }
-
+            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
+            using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
+            var msDecrypt = new MemoryStream();
+            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
+            var tmp = new byte[tmpFileStream.Length];
+            tmpFileStream.Read(tmp, 0, tmp.Length);
+            csDecrypt.Write(tmp, 0, tmp.Length);
+            csDecrypt.FlushFinalBlock();
+            var decrypted = msDecrypt.ToArray();
+            var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
+            return r;
         }
 
         #endregion
@@ -1283,54 +1253,50 @@ namespace Masuit.Tools.Security
         /// <param name="IV">初始化向量</param>
         /// <param name="Key">加密密匙</param>
         /// <returns>是否操作成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
+        public static void EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
         {
-            var r = false;
             if ((dataIndex > 10) && (dataIndex < 1))
             {
-                return r;
+                return;
             }
             //打开要写入的文件,主要是为了保持原文件的内容不丢失
-            var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-
+            using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
             var index = new byte[10261];
             //将读取的内容写到byte数组
-            tmpFileStream.Read(index, 0, 10261);
-            tmpFileStream.Close();
+            fs.Read(index, 0, 10261);
+
             //定义基本的加密转换运算
-            using (var encryptor = _rc2Csp.CreateEncryptor(Key, IV))
+            using var encryptor = _rc2Csp.CreateEncryptor(Key, IV);
+            var msEncrypt = new MemoryStream();
+            //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
+            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
+            var tmp = _textConverter.GetBytes(toEncryptText);
+            //将tmp输入csEncrypt,将通过Encryptor来加密。
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            //输出到msEnctypt
+            csEncrypt.FlushFinalBlock();
+
+            //将流转成byte[]
+            var encrypted = msEncrypt.ToArray();
+            if (encrypted.Length > 1024)
             {
-                var msEncrypt = new MemoryStream();
-                //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
-                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
-                {
-                    var tmp = _textConverter.GetBytes(toEncryptText);
-                    //将tmp输入csEncrypt,将通过Encryptor来加密。
-                    csEncrypt.Write(tmp, 0, tmp.Length);
-                    //输出到msEnctypt
-                    csEncrypt.FlushFinalBlock();
-                }
+                return;
+            }
 
-                //将流转成byte[]
-                var encrypted = msEncrypt.ToArray();
-                if (encrypted.Length > 1024)
-                    return false;
-                //得到加密后数据的大小,将结果存在指定的位置。
-                index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
-                index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
-                //将加密后的结果写入index(覆盖)
-                for (var i = 0; i < encrypted.Length; i++)
-                    index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
-                //建立文件流
-                tmpFileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
-                //写文件
-                tmpFileStream.Write(index, 0, 10261);
-                tmpFileStream.Flush();
-                r = true;
-                tmpFileStream.Close();
-                return r;
+            //得到加密后数据的大小,将结果存在指定的位置。
+            index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
+            index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
+            //将加密后的结果写入index(覆盖)
+            for (int i = 0; i < encrypted.Length; i++)
+            {
+                index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
             }
 
+            //建立文件流
+            using var newStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
+            newStream.Write(index, 0, 10261);
+            newStream.Flush();
+            newStream.Close();
         }
 
         #endregion
@@ -1347,35 +1313,26 @@ namespace Masuit.Tools.Security
         /// <returns>解密后的文本</returns>
         public static string DecryptFromFile(this string filePath, int dataIndex, byte[] iv, byte[] key)
         {
-            var r = "";
             if ((dataIndex > 10) && (dataIndex < 1))
             {
-                return r;
+                return "";
             }
 
-            using (var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
-            {
-                using (var decryptor = _rc2Csp.CreateDecryptor(key, iv))
-                {
-                    var msDecrypt = new MemoryStream();
-                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
-                    {
-                        var index = new byte[10261];
-
-                        tmpFileStream.Read(index, 0, 10261);
-                        var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
-                        var tmp = new byte[count];
+            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
+            using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
+            var msDecrypt = new MemoryStream();
+            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
+            var index = new byte[10261];
 
-                        Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
-                        csDecrypt.Write(tmp, 0, count);
-                        csDecrypt.FlushFinalBlock();
-                        var decrypted = msDecrypt.ToArray();
-                        r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-                    }
-                }
-            }
+            tmpFileStream.Read(index, 0, 10261);
+            var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
+            var tmp = new byte[count];
 
-            return r;
+            Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
+            csDecrypt.Write(tmp, 0, count);
+            csDecrypt.FlushFinalBlock();
+            var decrypted = msDecrypt.ToArray();
+            return _textConverter.GetString(decrypted, 0, decrypted.Length);
         }
 
         #endregion
@@ -1390,26 +1347,18 @@ namespace Masuit.Tools.Security
         /// <param name="iv">初始化向量</param>
         /// <param name="key">加密密匙</param>
         /// <returns>是否加密成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
+        public static void EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
         {
-            using (var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true))
-            {
-                using (var encryptor = _rc2Csp.CreateEncryptor(key, iv))
-                {
-                    var msEncrypt = new MemoryStream();
-                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = _textConverter.GetBytes(toEncryptText);
-                        csEncrypt.Write(tmp, 0, tmp.Length);
-                        csEncrypt.FlushFinalBlock();
-                        var encrypted = msEncrypt.ToArray();
-                        tmpFileStream.Write(encrypted, 0, encrypted.Length);
-                        tmpFileStream.Flush();
-                        var r = true;
-                        return r;
-                    }
-                }
-            }
+            using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
+            using var encryptor = _rc2Csp.CreateEncryptor(key, iv);
+            var msEncrypt = new MemoryStream();
+            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
+            var tmp = _textConverter.GetBytes(toEncryptText);
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            csEncrypt.FlushFinalBlock();
+            var encrypted = msEncrypt.ToArray();
+            tmpFileStream.Write(encrypted, 0, encrypted.Length);
+            tmpFileStream.Flush();
         }
 
         #endregion
@@ -1425,23 +1374,16 @@ namespace Masuit.Tools.Security
         /// <returns>解密后的文本</returns>
         public static string DecryptFromFile(this string filePath, byte[] iv, byte[] key)
         {
-            using (var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
-            {
-                using (var decryptor = _rc2Csp.CreateDecryptor(key, iv))
-                {
-                    var msDecrypt = new MemoryStream();
-                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = new byte[tmpFileStream.Length];
-                        tmpFileStream.Read(tmp, 0, tmp.Length);
-                        csDecrypt.Write(tmp, 0, tmp.Length);
-                        csDecrypt.FlushFinalBlock();
-                        var decrypted = msDecrypt.ToArray();
-                        var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-                        return r;
-                    }
-                }
-            }
+            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
+            using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
+            var msDecrypt = new MemoryStream();
+            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
+            var tmp = new byte[tmpFileStream.Length];
+            tmpFileStream.Read(tmp, 0, tmp.Length);
+            csDecrypt.Write(tmp, 0, tmp.Length);
+            csDecrypt.FlushFinalBlock();
+            var decrypted = msDecrypt.ToArray();
+            return _textConverter.GetString(decrypted, 0, decrypted.Length);
         }
 
         #endregion

+ 11 - 19
Masuit.Tools.Core/Security/RSACrypt.cs

@@ -36,14 +36,12 @@ namespace Masuit.Tools.Security
         /// </summary>
         public static RsaKey GenerateRsaKeys()
         {
-            using (var rsa = new RSACryptoServiceProvider())
+            using var rsa = new RSACryptoServiceProvider();
+            return RsaKey ??= new RsaKey
             {
-                return RsaKey ?? (RsaKey = new RsaKey
-                {
-                    PrivateKey = rsa.ToXmlString(true),
-                    PublicKey = rsa.ToXmlString(false)
-                });
-            }
+                PrivateKey = rsa.ToXmlString(true),
+                PublicKey = rsa.ToXmlString(false)
+            };
         }
 
         #endregion
@@ -189,7 +187,7 @@ namespace Masuit.Tools.Security
         public static string GetHashString(this string mStrSource)
         {
             //从字符串中取得Hash描述 
-            HashAlgorithm md5 = HashAlgorithm.Create("MD5");
+            var md5 = HashAlgorithm.Create("MD5");
             var buffer = Encoding.UTF8.GetBytes(mStrSource);
             var hashData = md5?.ComputeHash(buffer);
             return Convert.ToBase64String(hashData);
@@ -203,11 +201,8 @@ namespace Masuit.Tools.Security
         public static byte[] GetHashBytes(this FileStream objFile)
         {
             //从文件中取得Hash描述 
-            using (objFile)
-            {
-                HashAlgorithm md5 = HashAlgorithm.Create("MD5");
-                return md5?.ComputeHash(objFile);
-            }
+            var md5 = HashAlgorithm.Create("MD5");
+            return md5?.ComputeHash(objFile);
         }
 
         /// <summary>
@@ -218,12 +213,9 @@ namespace Masuit.Tools.Security
         public static string GetHashString(this FileStream objFile)
         {
             //从文件中取得Hash描述 
-            using (objFile)
-            {
-                HashAlgorithm md5 = HashAlgorithm.Create("MD5");
-                var hashData = md5?.ComputeHash(objFile);
-                return Convert.ToBase64String(hashData);
-            }
+            HashAlgorithm md5 = HashAlgorithm.Create("MD5");
+            var hashData = md5?.ComputeHash(objFile);
+            return Convert.ToBase64String(hashData);
         }
 
         #endregion

+ 41 - 47
Masuit.Tools.Core/Strings/ValidateCode.cs

@@ -44,57 +44,51 @@ namespace Masuit.Tools.Strings
         /// <exception cref="Exception">The operation failed.</exception>
         public static byte[] CreateValidateGraphic(this HttpContext context, string validateCode, int fontSize = 22, int lineHeight = 36)
         {
-            using (Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * (fontSize + 2.0)), lineHeight))
+            using Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * (fontSize + 2.0)), lineHeight);
+            using Graphics g = Graphics.FromImage(image);
+            //生成随机生成器
+            Random random = new Random();
+            //清空图片背景色
+            g.Clear(Color.White);
+            //画图片的干扰线
+            for (int i = 0; i < 75; i++)
             {
-                using (Graphics g = Graphics.FromImage(image))
-                {
-                    //生成随机生成器
-                    Random random = new Random();
-                    //清空图片背景色
-                    g.Clear(Color.White);
-                    //画图片的干扰线
-                    for (int i = 0; i < 75; i++)
-                    {
-                        int x1 = random.Next(image.Width);
-                        int x2 = random.Next(image.Width);
-                        int y1 = random.Next(image.Height);
-                        int y2 = random.Next(image.Height);
-                        g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
-                    }
-
-                    Font[] fonts =
-                    {
-                        new Font("Arial", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("微软雅黑", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("黑体", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("宋体", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("楷体", fontSize, FontStyle.Bold | FontStyle.Italic)
-                    };
-                    //渐变.
-                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
-                    g.DrawString(validateCode, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
+                int x1 = random.Next(image.Width);
+                int x2 = random.Next(image.Width);
+                int y1 = random.Next(image.Height);
+                int y2 = random.Next(image.Height);
+                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
+            }
 
-                    //画图片的前景干扰点
-                    for (int i = 0; i < 300; i++)
-                    {
-                        int x = random.Next(image.Width);
-                        int y = random.Next(image.Height);
-                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
-                    }
+            Font[] fonts =
+            {
+                new Font("Arial", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("微软雅黑", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("黑体", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("宋体", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("楷体", fontSize, FontStyle.Bold | FontStyle.Italic)
+            };
+            //渐变.
+            var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
+            g.DrawString(validateCode, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
 
-                    //画图片的边框线
-                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
-                    //保存图片数据
-                    using (MemoryStream stream = new MemoryStream())
-                    {
-                        image.Save(stream, ImageFormat.Jpeg);
-                        //输出图片流
-                        context.Response.Clear();
-                        context.Response.ContentType = "image/jpeg";
-                        return stream.ToArray();
-                    }
-                }
+            //画图片的前景干扰点
+            for (int i = 0; i < 300; i++)
+            {
+                int x = random.Next(image.Width);
+                int y = random.Next(image.Height);
+                image.SetPixel(x, y, Color.FromArgb(random.Next()));
             }
+
+            //画图片的边框线
+            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
+            //保存图片数据
+            using MemoryStream stream = new MemoryStream();
+            image.Save(stream, ImageFormat.Jpeg);
+            //输出图片流
+            context.Response.Clear();
+            context.Response.ContentType = "image/jpeg";
+            return stream.ToArray();
         }
     }
 }

+ 5 - 5
Masuit.Tools.Core/Systems/EnumExt.cs

@@ -42,7 +42,7 @@ namespace Masuit.Tools.Systems
             Dictionary<int, string> names = new Dictionary<int, string>(enumItems.Length);
             foreach (FieldInfo enumItem in enumItems)
             {
-                int intValue = (int) enumItem.GetValue(enumType);
+                int intValue = (int)enumItem.GetValue(enumType);
                 names[intValue] = enumItem.Name;
             }
 
@@ -73,7 +73,7 @@ namespace Masuit.Tools.Systems
             Dictionary<string, int> values = new Dictionary<string, int>(enumItems.Length);
             foreach (FieldInfo enumItem in enumItems)
             {
-                values[enumItem.Name] = (int) enumItem.GetValue(enumType);
+                values[enumItem.Name] = (int)enumItem.GetValue(enumType);
             }
 
             return values;
@@ -101,7 +101,7 @@ namespace Masuit.Tools.Systems
         /// <returns></returns>
         public static Type GetEnumType(Assembly assembly, string typeName)
         {
-            _enumTypeDict = _enumTypeDict ?? LoadEnumTypeDict(assembly);
+            _enumTypeDict ??= LoadEnumTypeDict(assembly);
             if (_enumTypeDict.ContainsKey(typeName))
             {
                 return _enumTypeDict[typeName];
@@ -127,7 +127,7 @@ namespace Masuit.Tools.Systems
             Dictionary<string, int> dicResult = new Dictionary<string, int>();
             foreach (object e in Enum.GetValues(enumType))
             {
-                dicResult.Add(GetDescription(e as Enum), (int) e);
+                dicResult.Add(GetDescription(e as Enum), (int)e);
             }
 
             return dicResult;
@@ -198,7 +198,7 @@ namespace Masuit.Tools.Systems
             {
                 if (field.FieldType.IsEnum)
                 {
-                    var strValue = ((int) enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
+                    var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                     nvc.Add(strValue, field.Name);
                 }
             }

+ 1 - 1
Masuit.Tools.Core/Systems/SnowFlake.cs

@@ -46,7 +46,7 @@ namespace Masuit.Tools.Systems
         /// <returns></returns>
         public static SnowFlake GetInstance()
         {
-            return _snowFlake ?? (_snowFlake = new SnowFlake());
+            return _snowFlake ??= new SnowFlake();
         }
 
         /// <summary>

+ 73 - 103
Masuit.Tools.Core/Win32/Windows.cs

@@ -21,7 +21,7 @@ namespace Masuit.Tools.Win32
         public static string GetLocalUsedIP()
         {
             string result = RunApp("route", "print", true);
-            Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
+            var m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
             if (m.Success)
             {
                 return m.Groups[2].Value;
@@ -29,12 +29,9 @@ namespace Masuit.Tools.Win32
 
             try
             {
-                string ip;
-                using (System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient())
-                {
-                    c.Connect("www.baidu.com", 80);
-                    ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
-                }
+                using var c = new System.Net.Sockets.TcpClient();
+                c.Connect("www.baidu.com", 80);
+                var ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
 
                 return ip;
             }
@@ -73,22 +70,23 @@ namespace Masuit.Tools.Win32
                 };
                 proc.Start();
 
-                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
+                using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
+                //上面标记的是原文,下面是我自己调试错误后自行修改的  
+                Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
+                //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
+                if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
                 {
-                    //上面标记的是原文,下面是我自己调试错误后自行修改的  
-                    Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                    //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                    if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                    {
-                        //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
-                        proc.Kill();
-                    }
+                    //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
+                    proc.Kill();
+                }
 
-                    string txt = sr.ReadToEnd();
-                    if (recordLog)
-                        Trace.WriteLine(txt);
-                    return txt;
+                string txt = sr.ReadToEnd();
+                if (recordLog)
+                {
+                    Trace.WriteLine(txt);
                 }
+
+                return txt;
             }
             catch (Exception ex)
             {
@@ -196,14 +194,12 @@ namespace Masuit.Tools.Win32
             {
                 //获取CPU序列号代码 
                 string cpuInfo = " "; //cpu序列号 
-                using (var mc = new ManagementClass("Win32_Processor"))
+                using var mc = new ManagementClass("Win32_Processor");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
-                        {
-                            cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
-                        }
+                        cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                     }
                 }
 
@@ -223,13 +219,9 @@ namespace Masuit.Tools.Win32
         {
             try
             {
-                using (var mCpu = new ManagementClass("Win32_Processor"))
-                {
-                    using (ManagementObjectCollection cpus = mCpu.GetInstances())
-                    {
-                        return cpus.Count;
-                    }
-                }
+                using var mCpu = new ManagementClass("Win32_Processor");
+                using var cpus = mCpu.GetInstances();
+                return cpus.Count;
             }
             catch
             {
@@ -245,27 +237,21 @@ namespace Masuit.Tools.Win32
         /// <returns></returns>
         public static string[] GetCpuMHZ()
         {
-            using (var mc = new ManagementClass("Win32_Processor"))
+            using var mc = new ManagementClass("Win32_Processor");
+            using ManagementObjectCollection cpus = mc.GetInstances();
+            var mhz = new string[cpus.Count];
+            int c = 0;
+            using var mySearch = new ManagementObjectSearcher("select * from Win32_Processor");
+            foreach (ManagementObject mo in mySearch.Get())
             {
-                using (ManagementObjectCollection cpus = mc.GetInstances())
+                using (mo)
                 {
-                    var mhz = new string[cpus.Count];
-                    int c = 0;
-                    using (var mySearch = new ManagementObjectSearcher("select * from Win32_Processor"))
-                    {
-                        foreach (ManagementObject mo in mySearch.Get())
-                        {
-                            using (mo)
-                            {
-                                mhz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
-                                c++;
-                            }
-                        }
-                    }
-
-                    return mhz;
+                    mhz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
+                    c++;
                 }
             }
+
+            return mhz;
         }
 
         /// <summary>
@@ -274,14 +260,12 @@ namespace Masuit.Tools.Win32
         /// <returns></returns>
         public static string GetSizeOfDisk()
         {
-            using (var mc = new ManagementClass("Win32_DiskDrive"))
+            using var mc = new ManagementClass("Win32_DiskDrive");
+            foreach (ManagementObject m in mc.GetInstances())
             {
-                foreach (ManagementObject m in mc.GetInstances())
+                using (m)
                 {
-                    using (m)
-                    {
-                        return m.Properties["Size"].Value.ToString();
-                    }
+                    return m.Properties["Size"].Value.ToString();
                 }
             }
 
@@ -294,17 +278,15 @@ namespace Masuit.Tools.Win32
             {
                 //获取网卡硬件地址 
                 string mac = " ";
-                using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
+                        if ((bool)mo["IPEnabled"])
                         {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                mac = mo["MacAddress"].ToString();
-                                break;
-                            }
+                            mac = mo["MacAddress"].ToString();
+                            break;
                         }
                     }
                 }
@@ -323,20 +305,18 @@ namespace Masuit.Tools.Win32
             {
                 //获取IP地址 
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
+                        if ((bool)mo["IPEnabled"])
                         {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                //st=mo[ "IpAddress "].ToString(); 
-                                Array ar;
-                                ar = (Array)(mo.Properties["IpAddress"].Value);
-                                st = ar.GetValue(0).ToString();
-                                break;
-                            }
+                            //st=mo[ "IpAddress "].ToString(); 
+                            Array ar;
+                            ar = (Array)(mo.Properties["IpAddress"].Value);
+                            st = ar.GetValue(0).ToString();
+                            break;
                         }
                     }
                 }
@@ -355,14 +335,12 @@ namespace Masuit.Tools.Win32
             {
                 //获取硬盘ID 
                 string hdid = Empty;
-                using (var mc = new ManagementClass("Win32_DiskDrive"))
+                using var mc = new ManagementClass("Win32_DiskDrive");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
-                        {
-                            hdid = (string)mo.Properties["Model"].Value;
-                        }
+                        hdid = (string)mo.Properties["Model"].Value;
                     }
                 }
 
@@ -383,14 +361,12 @@ namespace Masuit.Tools.Win32
             try
             {
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_ComputerSystem"))
+                using var mc = new ManagementClass("Win32_ComputerSystem");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
-                        {
-                            st = mo["UserName"].ToString();
-                        }
+                        st = mo["UserName"].ToString();
                     }
                 }
 
@@ -407,15 +383,13 @@ namespace Masuit.Tools.Win32
             try
             {
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_ComputerSystem"))
+                using var mc = new ManagementClass("Win32_ComputerSystem");
+                foreach (var o in mc.GetInstances())
                 {
-                    foreach (var o in mc.GetInstances())
+                    using (o)
                     {
-                        using (o)
-                        {
-                            var mo = (ManagementObject)o;
-                            st = mo["SystemType"].ToString();
-                        }
+                        var mo = (ManagementObject)o;
+                        st = mo["SystemType"].ToString();
                     }
                 }
 
@@ -432,17 +406,13 @@ namespace Masuit.Tools.Win32
             try
             {
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_ComputerSystem"))
+                using var mc = new ManagementClass("Win32_ComputerSystem");
+                using var moc = mc.GetInstances();
+                foreach (var o in moc)
                 {
-                    using (ManagementObjectCollection moc = mc.GetInstances())
-                    {
-                        foreach (var o in moc)
-                        {
-                            var mo = (ManagementObject)o;
+                    var mo = (ManagementObject)o;
 
-                            st = mo["TotalPhysicalMemory"].ToString();
-                        }
-                    }
+                    st = mo["TotalPhysicalMemory"].ToString();
                 }
 
                 return st;

+ 20 - 22
Masuit.Tools.Core/Win32/WindowsCommand.cs

@@ -23,31 +23,29 @@ namespace Masuit.Tools.Win32
             string output = "";
             if (!string.IsNullOrEmpty(dosCommand))
             {
-                using (Process process = new Process()) //创建进程对象  
-                {
-                    ProcessStartInfo startinfo = new ProcessStartInfo(); //创建进程时使用的一组值,如下面的属性  
-                    startinfo.FileName = "cmd.exe"; //设定需要执行的命令程序  
-                    //以下是隐藏cmd窗口的方法  
-                    startinfo.Arguments = "/c" + dosCommand; //设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出  
-                    startinfo.UseShellExecute = false; //不使用系统外壳程序启动  
-                    startinfo.RedirectStandardInput = false; //不重定向输入  
-                    startinfo.RedirectStandardOutput = true; //重定向输出,而不是默认的显示在dos控制台上  
-                    startinfo.CreateNoWindow = true; //不创建窗口  
-                    process.StartInfo = startinfo;
+                using var process = new Process();
+                ProcessStartInfo startinfo = new ProcessStartInfo(); //创建进程时使用的一组值,如下面的属性  
+                startinfo.FileName = "cmd.exe"; //设定需要执行的命令程序  
+                //以下是隐藏cmd窗口的方法  
+                startinfo.Arguments = "/c" + dosCommand; //设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出  
+                startinfo.UseShellExecute = false; //不使用系统外壳程序启动  
+                startinfo.RedirectStandardInput = false; //不重定向输入  
+                startinfo.RedirectStandardOutput = true; //重定向输出,而不是默认的显示在dos控制台上  
+                startinfo.CreateNoWindow = true; //不创建窗口  
+                process.StartInfo = startinfo;
 
-                    if (process.Start()) //开始进程  
+                if (process.Start()) //开始进程  
+                {
+                    if (outtime == 0)
                     {
-                        if (outtime == 0)
-                        {
-                            process.WaitForExit();
-                        }
-                        else
-                        {
-                            process.WaitForExit(outtime);
-                        }
-
-                        output = process.StandardOutput.ReadToEnd(); //读取进程的输出  
+                        process.WaitForExit();
                     }
+                    else
+                    {
+                        process.WaitForExit(outtime);
+                    }
+
+                    output = process.StandardOutput.ReadToEnd(); //读取进程的输出  
                 }
 
                 return output;

+ 1 - 0
Masuit.Tools.ExpressionMapperBenchmark/Masuit.Tools.ExpressionMapperBenchmark.csproj

@@ -3,6 +3,7 @@
   <PropertyGroup>
     <OutputType>Exe</OutputType>
     <TargetFramework>netcoreapp3.0</TargetFramework>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
   <ItemGroup>

+ 1 - 0
Masuit.Tools.NoSQL.MongoDBClient/Masuit.Tools.NoSQL.MongoDBClient.csproj

@@ -18,6 +18,7 @@
     <Product>Masuit.Tools.NoSQL.MongoDBClient</Product>
     <PackageId>Masuit.Tools.NoSQL.MongoDBClient</PackageId>
     <PackageRequireLicenseAcceptance>False</PackageRequireLicenseAcceptance>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

+ 1 - 1
Masuit.Tools.UnitTest/ExtensionMethodsTest.cs

@@ -30,7 +30,7 @@ namespace Masuit.Tools.UnitTest
         [Theory]
         [InlineData("16666666666")]
         [InlineData("19999999999")]
-        public async void Can_MatchPhoneNumber_(string phone)
+        public void Can_MatchPhoneNumber_(string phone)
         {
             Xunit.Assert.True(phone.MatchPhoneNumber());
         }

+ 2 - 0
Masuit.Tools.UnitTest/Masuit.Tools.UnitTest.csproj

@@ -31,6 +31,7 @@
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
@@ -39,6 +40,7 @@
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="Castle.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">

+ 5 - 12
Masuit.Tools/Database/DataTableHelper.cs

@@ -51,21 +51,14 @@ namespace Masuit.Tools.Database
         public static List<T> ToList<T>(this DataTable dt) where T : class, new()
         {
             List<T> list = new List<T>();
-            using (dt)
+            if (dt == null || dt.Rows.Count == 0)
             {
-                if (dt == null || dt.Rows.Count == 0)
-                {
-                    return list;
-                }
-
-                DataTableBuilder<T> eblist = DataTableBuilder<T>.CreateBuilder(dt.Rows[0]);
-                foreach (DataRow info in dt.Rows)
-                {
-                    list.Add(eblist.Build(info));
-                }
-
                 return list;
             }
+
+            list.AddRange(dt.Rows.Cast<DataRow>().Select(info => DataTableBuilder<T>.CreateBuilder(dt.Rows[0]).Build(info)));
+
+            return list;
         }
 
         /// <summary>

+ 18 - 27
Masuit.Tools/Files/FileExt.cs

@@ -18,14 +18,12 @@ namespace Masuit.Tools.Files
         /// <param name="bufferSize">缓冲区大小,默认8MB</param>
         public static void CopyToFile(this Stream fs, string dest, int bufferSize = 1024 * 8 * 1024)
         {
-            using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            using var fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            byte[] buf = new byte[bufferSize];
+            int len;
+            while ((len = fs.Read(buf, 0, buf.Length)) != 0)
             {
-                byte[] buf = new byte[bufferSize];
-                int len = 0;
-                while ((len = fs.Read(buf, 0, buf.Length)) != 0)
-                {
-                    fsWrite.Write(buf, 0, len);
-                }
+                fsWrite.Write(buf, 0, len);
             }
         }
 
@@ -37,21 +35,16 @@ namespace Masuit.Tools.Files
         /// <param name="bufferSize">缓冲区大小,默认8MB</param>
         public static async void CopyToFileAsync(this Stream fs, string dest, int bufferSize = 1024 * 1024 * 8)
         {
-            using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            using var fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            byte[] buf = new byte[bufferSize];
+            int len;
+            await Task.Run(() =>
             {
-                byte[] buf = new byte[bufferSize];
-                int len;
-                await Task.Run(() =>
+                while ((len = fs.Read(buf, 0, buf.Length)) != 0)
                 {
-                    using (fs)
-                    {
-                        while ((len = fs.Read(buf, 0, buf.Length)) != 0)
-                        {
-                            fsWrite.Write(buf, 0, len);
-                        }
-                    }
-                }).ConfigureAwait(true);
-            }
+                    fsWrite.Write(buf, 0, len);
+                }
+            }).ConfigureAwait(true);
         }
 
         /// <summary>
@@ -61,13 +54,11 @@ namespace Masuit.Tools.Files
         /// <param name="filename"></param>
         public static void SaveFile(this MemoryStream ms, string filename)
         {
-            using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
-            {
-                byte[] buffer = ms.ToArray(); // 转化为byte格式存储
-                fs.Write(buffer, 0, buffer.Length);
-                fs.Flush();
-                buffer = null;
-            }
+            using var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            byte[] buffer = ms.ToArray(); // 转化为byte格式存储
+            fs.Write(buffer, 0, buffer.Length);
+            fs.Flush();
+            buffer = null;
         }
 
         /// <summary>

+ 94 - 70
Masuit.Tools/Hardware/SystemInfo.cs

@@ -6,6 +6,7 @@ using System.Collections.Generic;
 using System.Diagnostics;
 using System.Management;
 using System.Net;
+using System.Net.Sockets;
 using System.Runtime.InteropServices;
 using System.Text;
 using System.Text.RegularExpressions;
@@ -46,8 +47,10 @@ namespace Masuit.Tools.Hardware
         static SystemInfo()
         {
             //初始化CPU计数器 
-            PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
-            PcCpuLoad.MachineName = ".";
+            PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
+            {
+                MachineName = "."
+            };
             PcCpuLoad.NextValue();
 
             //CPU个数 
@@ -69,10 +72,12 @@ namespace Masuit.Tools.Hardware
                 PerformanceCounterCategory cat = new PerformanceCounterCategory("Network Interface");
                 InstanceNames = cat.GetInstanceNames();
                 NetRecvCounters = new PerformanceCounter[InstanceNames.Length];
-                for (int i = 0; i < InstanceNames.Length; i++) NetRecvCounters[i] = new PerformanceCounter();
-
                 NetSentCounters = new PerformanceCounter[InstanceNames.Length];
-                for (int i = 0; i < InstanceNames.Length; i++) NetSentCounters[i] = new PerformanceCounter();
+                for (int i = 0; i < InstanceNames.Length; i++)
+                {
+                    NetRecvCounters[i] = new PerformanceCounter();
+                    NetSentCounters[i] = new PerformanceCounter();
+                }
 
                 CompactFormat = false;
             }
@@ -120,7 +125,10 @@ namespace Masuit.Tools.Hardware
                     foreach (var o in mos.GetInstances())
                     {
                         var mo = (ManagementObject)o;
-                        if (mo["FreePhysicalMemory"] != null) availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
+                        if (mo["FreePhysicalMemory"] != null)
+                        {
+                            availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
+                        }
                     }
 
                     return availablebytes;
@@ -153,7 +161,6 @@ namespace Masuit.Tools.Hardware
         public static ArrayList FindAllApps(int handle)
         {
             ArrayList apps = new ArrayList();
-
             int hwCurr = GetWindow(handle, GwHwndfirst);
 
             while (hwCurr > 0)
@@ -167,7 +174,10 @@ namespace Masuit.Tools.Hardware
                     StringBuilder sb = new StringBuilder(2 * length + 1);
                     GetWindowText(hwCurr, sb, sb.Capacity);
                     string strTitle = sb.ToString();
-                    if (!string.IsNullOrEmpty(strTitle)) apps.Add(strTitle);
+                    if (!string.IsNullOrEmpty(strTitle))
+                    {
+                        apps.Add(strTitle);
+                    }
                 }
 
                 hwCurr = GetWindow(hwCurr, GwHwndnext);
@@ -246,15 +256,17 @@ namespace Masuit.Tools.Hardware
         /// 获取内存信息
         /// </summary>
         /// <returns>内存信息</returns>
-        public static RamInfo GetRamInfo() => new RamInfo
+        public static RamInfo GetRamInfo()
         {
-            MemoryAvailable = GetFreePhysicalMemory(),
-            PhysicalMemory = GetTotalPhysicalMemory(),
-            TotalPageFile = GetTotalVirtualMemory(),
-            AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory(),
-            AvailableVirtual = 1 - GetUsageVirtualMemory(),
-            TotalVirtual = 1 - GetUsedPhysicalMemory()
-        };
+            var info = new RamInfo();
+            info.MemoryAvailable = GetFreePhysicalMemory();
+            info.PhysicalMemory = GetTotalPhysicalMemory();
+            info.TotalPageFile = GetTotalVirtualMemory();
+            info.AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory();
+            info.AvailableVirtual = 1 - GetUsageVirtualMemory();
+            info.TotalVirtual = 1 - GetUsedPhysicalMemory();
+            return info;
+        }
 
         #endregion
 
@@ -375,7 +387,7 @@ namespace Masuit.Tools.Hardware
         public static double GetTotalPhysicalMemory()
         {
             string s = QueryComputerSystem("totalphysicalmemory");
-            return Convert.ToDouble(s);
+            return s.ToDouble();
         }
 
         /// <summary>
@@ -418,10 +430,32 @@ namespace Masuit.Tools.Hardware
         /// <returns></returns>
         public static double GetNetData(NetData nd)
         {
-            if (InstanceNames.Length == 0) return 0;
+            if (InstanceNames.Length == 0)
+            {
+                return 0;
+            }
 
             double d = 0;
-            for (int i = 0; i < InstanceNames.Length; i++) d += nd == NetData.Received ? GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]) : nd == NetData.Sent ? GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]) : nd == NetData.ReceivedAndSent ? GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]) + GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]) : 0;
+            for (int i = 0; i < InstanceNames.Length; i++)
+            {
+                double receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]);
+                double send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]);
+                switch (nd)
+                {
+                    case NetData.Received:
+                        d += receied;
+                        break;
+                    case NetData.Sent:
+                        d += send;
+                        break;
+                    case NetData.ReceivedAndSent:
+                        d += receied + send;
+                        break;
+                    default:
+                        d += 0;
+                        break;
+                }
+            }
 
             return d;
         }
@@ -438,19 +472,13 @@ namespace Masuit.Tools.Hardware
             try
             {
                 IList<string> list = new List<string>();
-                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                using (mc)
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                using var moc = mc.GetInstances();
+                foreach (ManagementObject mo in moc)
                 {
-                    ManagementObjectCollection moc = mc.GetInstances();
-                    using (moc)
+                    if ((bool)mo["IPEnabled"])
                     {
-                        foreach (ManagementObject mo in moc)
-                        {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                list.Add(mo["MacAddress"].ToString());
-                            }
-                        }
+                        list.Add(mo["MacAddress"].ToString());
                     }
                 }
 
@@ -472,31 +500,25 @@ namespace Masuit.Tools.Hardware
             try
             {
                 IList<string> list = new List<string>();
-                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
-                using (mc)
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                using var moc = mc.GetInstances();
+                foreach (ManagementObject mo in moc)
                 {
-                    ManagementObjectCollection moc = mc.GetInstances();
-                    using (moc)
+                    if ((bool)mo["IPEnabled"])
                     {
-                        foreach (ManagementObject mo in moc)
-                        {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                var ar = (Array)(mo.Properties["IpAddress"].Value);
-                                var st = ar.GetValue(0).ToString();
-                                list.Add(st);
-                            }
-                        }
-
-                        return list;
+                        var ar = (Array)(mo.Properties["IpAddress"].Value);
+                        var st = ar.GetValue(0).ToString();
+                        list.Add(st);
                     }
                 }
+
+                return list;
             }
             catch (Exception)
             {
                 return new List<string>()
                 {
-                    "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。"
+                    "未能获取到当前计算机的IP地址,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。"
                 };
             }
         }
@@ -508,7 +530,7 @@ namespace Masuit.Tools.Hardware
         public static string GetLocalUsedIP()
         {
             string result = RunApp("route", "print", true);
-            Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
+            var m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)", RegexOptions.Compiled);
             if (m.Success)
             {
                 return m.Groups[2].Value;
@@ -516,15 +538,14 @@ namespace Masuit.Tools.Hardware
 
             try
             {
-                System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
+                using var c = new TcpClient();
                 c.Connect("www.baidu.com", 80);
-                string ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
-                c.Close();
+                var ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                 return ip;
             }
             catch (Exception)
             {
-                return "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
+                return "未能获取当前使用的IP,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
             }
         }
 
@@ -557,22 +578,22 @@ namespace Masuit.Tools.Hardware
                 };
                 proc.Start();
 
-                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
+                using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
+                Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
+                //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
+                if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
                 {
-                    Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                    //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                    if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                    {
-                        //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
-                        proc.Kill();
-                    }
+                    //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
+                    proc.Kill();
+                }
 
-                    string txt = sr.ReadToEnd();
-                    sr.Close();
-                    if (recordLog)
-                        Trace.WriteLine(txt);
-                    return txt;
+                string txt = sr.ReadToEnd();
+                sr.Close();
+                if (recordLog)
+                {
+                    Trace.WriteLine(txt);
                 }
+                return txt;
             }
             catch (Exception ex)
             {
@@ -649,12 +670,15 @@ namespace Masuit.Tools.Hardware
             {
                 string str = null;
                 ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
-                foreach (ManagementObject objMgmt in objCS.Get()) str = objMgmt[type].ToString();
+                foreach (ManagementObject objMgmt in objCS.Get())
+                {
+                    str = objMgmt[type].ToString();
+                }
                 return str;
             }
-            catch (Exception)
+            catch (Exception e)
             {
-                return "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
+                return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message;
             }
         }
 
@@ -702,7 +726,7 @@ namespace Masuit.Tools.Hardware
             {
                 return new Dictionary<string, string>()
                 {
-                    { "null", "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
+                    { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
                 };
             }
         }
@@ -769,7 +793,7 @@ namespace Masuit.Tools.Hardware
             {
                 return new Dictionary<string, string>()
                 {
-                    { "null", "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
+                    { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
                 };
             }
         }
@@ -804,7 +828,7 @@ namespace Masuit.Tools.Hardware
             {
                 return new Dictionary<string, double>()
                 {
-                    { "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 }
+                    { "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 }
                 };
             }
         }

+ 2 - 4
Masuit.Tools/Logging/LogManager.cs

@@ -440,10 +440,8 @@ namespace Masuit.Tools.Logging
                     File.CreateText(logPath).Close();
                 }
 
-                using (StreamWriter sw = File.AppendText(logPath))
-                {
-                    sw.Write(logContent);
-                }
+                using var sw = File.AppendText(logPath);
+                sw.Write(logContent);
             }
             catch (Exception)
             {

+ 1 - 1
Masuit.Tools/Mapping/Core/MapperConfigurationCollectionContainer.cs

@@ -22,7 +22,7 @@ namespace Masuit.Tools.Mapping.Core
         /// <summary>
         /// mapper映射容器
         /// </summary>
-        public static MapperConfigurationCollectionContainer Instance => currentInstance ?? (currentInstance = new MapperConfigurationCollectionContainer());
+        public static MapperConfigurationCollectionContainer Instance => currentInstance ??= new MapperConfigurationCollectionContainer();
 
         /// <summary>
         /// count

+ 5 - 0
Masuit.Tools/Masuit.Tools.csproj

@@ -27,6 +27,7 @@
     <DocumentationFile>bin\Debug\Masuit.Tools.XML</DocumentationFile>
     <NoWarn>1591</NoWarn>
     <CodeAnalysisRuleSet />
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
@@ -39,6 +40,10 @@
     <DocumentationFile>bin\Release\Masuit.Tools.XML</DocumentationFile>
     <NoWarn>1591</NoWarn>
     <CodeAnalysisRuleSet />
+    <LangVersion>8.0</LangVersion>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="AngleSharp, Version=0.13.0.0, Culture=neutral, PublicKeyToken=e83494dcdc6d31ea, processorArchitecture=MSIL">

+ 2 - 0
Masuit.Tools/Masuit.Tools.csproj.DotSettings

@@ -0,0 +1,2 @@
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+	<s:String x:Key="/Default/CodeInspection/CSharpLanguageProject/LanguageLevel/@EntryValue">CSharp80</s:String></wpf:ResourceDictionary>

+ 221 - 273
Masuit.Tools/Media/ImageUtilities.cs

@@ -293,13 +293,11 @@ namespace Masuit.Tools.Media
                 //文字水印
                 if (watermarkText != "")
                 {
-                    using (Graphics gWater = Graphics.FromImage(initImage))
-                    {
-                        Font fontWater = new Font("黑体", 10);
-                        Brush brushWater = new SolidBrush(Color.White);
-                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
-                        gWater.Dispose();
-                    }
+                    using var gWater = Graphics.FromImage(initImage);
+                    Font fontWater = new Font("黑体", 10);
+                    Brush brushWater = new SolidBrush(Color.White);
+                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
+                    gWater.Dispose();
                 }
 
                 //透明图片水印
@@ -307,38 +305,36 @@ namespace Masuit.Tools.Media
                 {
                     if (File.Exists(watermarkImage))
                     {
-                        using (Image wrImage = Image.FromFile(watermarkImage))
+                        using var wrImage = Image.FromFile(watermarkImage);
+                        //水印绘制条件:原始图片宽高均大于或等于水印图片
+                        if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
                         {
-                            //水印绘制条件:原始图片宽高均大于或等于水印图片
-                            if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
+                            Graphics gWater = Graphics.FromImage(initImage);
+
+                            //透明属性
+                            ImageAttributes imgAttributes = new ImageAttributes();
+                            ColorMap colorMap = new ColorMap();
+                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
+                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
+                            ColorMap[] remapTable = { colorMap };
+                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
+
+                            float[][] colorMatrixElements =
                             {
-                                Graphics gWater = Graphics.FromImage(initImage);
-
-                                //透明属性
-                                ImageAttributes imgAttributes = new ImageAttributes();
-                                ColorMap colorMap = new ColorMap();
-                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
-                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
-                                ColorMap[] remapTable = { colorMap };
-                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
-
-                                float[][] colorMatrixElements =
-                                {
-                                    new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
-                                    new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
-                                };
-
-                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
-                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
-                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
-
-                                gWater.Dispose();
-                            }
-                            wrImage.Dispose();
+                                new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
+                                new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
+                            };
+
+                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
+                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
+                            gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
+
+                            gWater.Dispose();
                         }
+                        wrImage.Dispose();
                     }
                 }
 
@@ -392,13 +388,11 @@ namespace Masuit.Tools.Media
                 //文字水印
                 if (watermarkText != "")
                 {
-                    using (Graphics gWater = Graphics.FromImage(newImage))
-                    {
-                        Font fontWater = new Font("宋体", 10);
-                        Brush brushWater = new SolidBrush(Color.White);
-                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
-                        gWater.Dispose();
-                    }
+                    using var gWater = Graphics.FromImage(newImage);
+                    Font fontWater = new Font("宋体", 10);
+                    Brush brushWater = new SolidBrush(Color.White);
+                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
+                    gWater.Dispose();
                 }
 
                 //透明图片水印
@@ -406,37 +400,35 @@ namespace Masuit.Tools.Media
                 {
                     if (File.Exists(watermarkImage))
                     {
-                        using (Image wrImage = Image.FromFile(watermarkImage))
+                        using Image wrImage = Image.FromFile(watermarkImage);
+                        //水印绘制条件:原始图片宽高均大于或等于水印图片
+                        if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
                         {
-                            //水印绘制条件:原始图片宽高均大于或等于水印图片
-                            if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
+                            Graphics gWater = Graphics.FromImage(newImage);
+
+                            //透明属性
+                            ImageAttributes imgAttributes = new ImageAttributes();
+                            ColorMap colorMap = new ColorMap();
+                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
+                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
+                            ColorMap[] remapTable = { colorMap };
+                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
+
+                            float[][] colorMatrixElements =
                             {
-                                Graphics gWater = Graphics.FromImage(newImage);
-
-                                //透明属性
-                                ImageAttributes imgAttributes = new ImageAttributes();
-                                ColorMap colorMap = new ColorMap();
-                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
-                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
-                                ColorMap[] remapTable = { colorMap };
-                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
-
-                                float[][] colorMatrixElements =
-                                {
-                                    new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
-                                    new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
-                                    new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
-                                };
-
-                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
-                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
-                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
-                                gWater.Dispose();
-                            }
-                            wrImage.Dispose();
+                                new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
+                                new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
+                                new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
+                            };
+
+                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
+                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
+                            gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
+                            gWater.Dispose();
                         }
+                        wrImage.Dispose();
                     }
                 }
 
@@ -570,79 +562,69 @@ namespace Masuit.Tools.Media
                 return true;
             }
 
-            using (Image iSource = Image.FromFile(sFile))
+            using Image iSource = Image.FromFile(sFile);
+            ImageFormat tFormat = iSource.RawFormat;
+            int dHeight = iSource.Height;
+            int dWidth = iSource.Width;
+            int sW, sH;
+            //按比例缩放
+            Size temSize = new Size(iSource.Width, iSource.Height);
+            if (temSize.Width > dHeight || temSize.Width > dWidth)
             {
-                ImageFormat tFormat = iSource.RawFormat;
-                int dHeight = iSource.Height;
-                int dWidth = iSource.Width;
-                int sW, sH;
-                //按比例缩放
-                Size temSize = new Size(iSource.Width, iSource.Height);
-                if (temSize.Width > dHeight || temSize.Width > dWidth)
+                if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
                 {
-                    if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
-                    {
-                        sW = dWidth;
-                        sH = (dWidth * temSize.Height) / temSize.Width;
-                    }
-                    else
-                    {
-                        sH = dHeight;
-                        sW = (temSize.Width * dHeight) / temSize.Height;
-                    }
+                    sW = dWidth;
+                    sH = (dWidth * temSize.Height) / temSize.Width;
                 }
                 else
                 {
-                    sW = temSize.Width;
-                    sH = temSize.Height;
+                    sH = dHeight;
+                    sW = (temSize.Width * dHeight) / temSize.Height;
                 }
+            }
+            else
+            {
+                sW = temSize.Width;
+                sH = temSize.Height;
+            }
 
-                using (Bitmap bmp = new Bitmap(dWidth, dHeight))
+            using Bitmap bmp = new Bitmap(dWidth, dHeight);
+            using Graphics g = Graphics.FromImage(bmp);
+            g.Clear(Color.WhiteSmoke);
+            g.CompositingQuality = CompositingQuality.HighQuality;
+            g.SmoothingMode = SmoothingMode.HighQuality;
+            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
+
+            //以下代码为保存图片时,设置压缩质量
+            using EncoderParameters ep = new EncoderParameters();
+            long[] qy = new long[1];
+            qy[0] = flag;//设置压缩的比例1-100
+            using EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
+            ep.Param[0] = eParam;
+            try
+            {
+                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
+                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
+                if (jpegIcIinfo != null)
                 {
-                    using (Graphics g = Graphics.FromImage(bmp))
-                    {
-                        g.Clear(Color.WhiteSmoke);
-                        g.CompositingQuality = CompositingQuality.HighQuality;
-                        g.SmoothingMode = SmoothingMode.HighQuality;
-                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-                    }
-
-                    //以下代码为保存图片时,设置压缩质量
-                    using (EncoderParameters ep = new EncoderParameters())
+                    bmp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
+                    FileInfo fi = new FileInfo(dFile);
+                    if (fi.Length > 1024 * size)
                     {
-                        long[] qy = new long[1];
-                        qy[0] = flag;//设置压缩的比例1-100
-                        using (EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy))
-                        {
-                            ep.Param[0] = eParam;
-                            try
-                            {
-                                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
-                                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
-                                if (jpegIcIinfo != null)
-                                {
-                                    bmp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
-                                    FileInfo fi = new FileInfo(dFile);
-                                    if (fi.Length > 1024 * size)
-                                    {
-                                        flag = flag - 10;
-                                        CompressImage(sFile, dFile, flag, size, false);
-                                    }
-                                }
-                                else
-                                {
-                                    bmp.Save(dFile, tFormat);
-                                }
-                                return true;
-                            }
-                            catch
-                            {
-                                return false;
-                            }
-                        }
+                        flag = flag - 10;
+                        CompressImage(sFile, dFile, flag, size, false);
                     }
                 }
+                else
+                {
+                    bmp.Save(dFile, tFormat);
+                }
+                return true;
+            }
+            catch
+            {
+                return false;
             }
         }
 
@@ -664,78 +646,68 @@ namespace Masuit.Tools.Media
                 return true;
             }
 
-            using (Image iSource = Image.FromStream(src))
+            using Image iSource = Image.FromStream(src);
+            ImageFormat tFormat = iSource.RawFormat;
+            int dHeight = iSource.Height;
+            int dWidth = iSource.Width;
+            int sW, sH;
+            //按比例缩放
+            Size temSize = new Size(iSource.Width, iSource.Height);
+            if (temSize.Width > dHeight || temSize.Width > dWidth)
             {
-                ImageFormat tFormat = iSource.RawFormat;
-                int dHeight = iSource.Height;
-                int dWidth = iSource.Width;
-                int sW, sH;
-                //按比例缩放
-                Size temSize = new Size(iSource.Width, iSource.Height);
-                if (temSize.Width > dHeight || temSize.Width > dWidth)
+                if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
                 {
-                    if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
-                    {
-                        sW = dWidth;
-                        sH = (dWidth * temSize.Height) / temSize.Width;
-                    }
-                    else
-                    {
-                        sH = dHeight;
-                        sW = (temSize.Width * dHeight) / temSize.Height;
-                    }
+                    sW = dWidth;
+                    sH = (dWidth * temSize.Height) / temSize.Width;
                 }
                 else
                 {
-                    sW = temSize.Width;
-                    sH = temSize.Height;
+                    sH = dHeight;
+                    sW = (temSize.Width * dHeight) / temSize.Height;
                 }
+            }
+            else
+            {
+                sW = temSize.Width;
+                sH = temSize.Height;
+            }
 
-                using (Bitmap bmp = new Bitmap(dWidth, dHeight))
+            using Bitmap bmp = new Bitmap(dWidth, dHeight);
+            using Graphics g = Graphics.FromImage(bmp);
+            g.Clear(Color.WhiteSmoke);
+            g.CompositingQuality = CompositingQuality.HighQuality;
+            g.SmoothingMode = SmoothingMode.HighQuality;
+            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
+
+            //以下代码为保存图片时,设置压缩质量
+            using EncoderParameters ep = new EncoderParameters();
+            long[] qy = new long[1];
+            qy[0] = flag;//设置压缩的比例1-100
+            using EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
+            ep.Param[0] = eParam;
+            try
+            {
+                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
+                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
+                if (jpegIcIinfo != null)
                 {
-                    using (Graphics g = Graphics.FromImage(bmp))
+                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
+                    if (dest.Length > 1024 * size)
                     {
-                        g.Clear(Color.WhiteSmoke);
-                        g.CompositingQuality = CompositingQuality.HighQuality;
-                        g.SmoothingMode = SmoothingMode.HighQuality;
-                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
-                    }
-
-                    //以下代码为保存图片时,设置压缩质量
-                    using (EncoderParameters ep = new EncoderParameters())
-                    {
-                        long[] qy = new long[1];
-                        qy[0] = flag;//设置压缩的比例1-100
-                        using (EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy))
-                        {
-                            ep.Param[0] = eParam;
-                            try
-                            {
-                                ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
-                                ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
-                                if (jpegIcIinfo != null)
-                                {
-                                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
-                                    if (dest.Length > 1024 * size)
-                                    {
-                                        flag = flag - 10;
-                                        CompressImage(src, dest, flag, size, false);
-                                    }
-                                }
-                                else
-                                {
-                                    bmp.Save(dest, tFormat);
-                                }
-                                return true;
-                            }
-                            catch
-                            {
-                                return false;
-                            }
-                        }
+                        flag = flag - 10;
+                        CompressImage(src, dest, flag, size, false);
                     }
                 }
+                else
+                {
+                    bmp.Save(dest, tFormat);
+                }
+                return true;
+            }
+            catch
+            {
+                return false;
             }
         }
 
@@ -932,18 +904,14 @@ namespace Masuit.Tools.Media
         {
             try
             {
-                using (Bitmap bap = new Bitmap(newW, newH))
+                using Bitmap bap = new Bitmap(newW, newH);
+                return await Task.Run(() =>
                 {
-                    return await Task.Run(() =>
-                    {
-                        using (Graphics g = Graphics.FromImage(bap))
-                        {
-                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-                            g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
-                        }
-                        return bap;
-                    }).ConfigureAwait(false);
-                }
+                    using Graphics g = Graphics.FromImage(bap);
+                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                    g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
+                    return bap;
+                }).ConfigureAwait(false);
             }
             catch (Exception)
             {
@@ -963,21 +931,18 @@ namespace Masuit.Tools.Media
         /// <param name="height">原始图片的高度</param>
         public static Bitmap FilPic(this Bitmap mybm, int width, int height)
         {
-            using (Bitmap bm = new Bitmap(width, height)) //初始化一个记录滤色效果的图片对象
+            using var bm = new Bitmap(width, height);
+            for (var x = 0; x < width; x++)
             {
-                int x, y;
-                Color pixel;
-                for (x = 0; x < width; x++)
+                int y;
+                for (y = 0; y < height; y++)
                 {
-                    for (y = 0; y < height; y++)
-                    {
-                        pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
-                        bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -992,20 +957,20 @@ namespace Masuit.Tools.Media
         /// <param name="height">原始图片的高度</param>
         public static Bitmap RevPicLR(this Bitmap mybm, int width, int height)
         {
-            using (Bitmap bm = new Bitmap(width, height))
+            using var bm = new Bitmap(width, height);
+            //x,y是循环次数,z是用来记录像素点的x坐标的变化的
+            for (var y = height - 1; y >= 0; y--)
             {
-                int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-                for (y = height - 1; y >= 0; y--)
+                int x; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
+                int z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
+                for (x = width - 1, z = 0; x >= 0; x--)
                 {
-                    for (x = width - 1, z = 0; x >= 0; x--)
-                    {
-                        var pixel = mybm.GetPixel(x, y);
-                        bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -1020,21 +985,19 @@ namespace Masuit.Tools.Media
         /// <param name="height">原始图片的高度</param>
         public static Bitmap RevPicUD(this Bitmap mybm, int width, int height)
         {
-            Bitmap bm = new Bitmap(width, height);
-            using (bm)
+            using var bm = new Bitmap(width, height);
+            for (var x = 0; x < width; x++)
             {
-                int x, y, z;
-                for (x = 0; x < width; x++)
+                int y;
+                int z;
+                for (y = height - 1, z = 0; y >= 0; y--)
                 {
-                    for (y = height - 1, z = 0; y >= 0; y--)
-                    {
-                        var pixel = mybm.GetPixel(x, y);
-                        bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -1110,22 +1073,18 @@ namespace Masuit.Tools.Media
         /// <param name="height">图片的高度</param>
         public static Bitmap BWPic(this Bitmap mybm, int width, int height)
         {
-            Bitmap bm = new Bitmap(width, height);
-            using (bm)
+            using var bm = new Bitmap(width, height);
+            for (var x = 0; x < width; x++)
             {
-                int x, y; //x,y是循环次数
-                for (x = 0; x < width; x++)
+                for (var y = 0; y < height; y++)
                 {
-                    for (y = 0; y < height; y++)
-                    {
-                        var pixel = mybm.GetPixel(x, y);
-                        var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素值
-                        bm.SetPixel(x, y, Color.FromArgb(result, result, result));
-                    }
+                    var pixel = mybm.GetPixel(x, y);
+                    var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素值
+                    bm.SetPixel(x, y, Color.FromArgb(result, result, result));
                 }
-
-                return bm;
             }
+
+            return bm;
         }
 
         #endregion
@@ -1139,15 +1098,12 @@ namespace Masuit.Tools.Media
         /// <param name="pSavedPath">保存路径</param>
         public static void GetFrames(this Image gif, string pSavedPath)
         {
-            using (gif)
+            var fd = new FrameDimension(gif.FrameDimensionsList[0]);
+            int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
+            for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
             {
-                FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
-                int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
-                for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
-                {
-                    gif.SelectActiveFrame(fd, i);
-                    gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
-                }
+                gif.SelectActiveFrame(fd, i);
+                gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
             }
         }
 
@@ -1162,23 +1118,15 @@ namespace Masuit.Tools.Media
         /// <exception cref="Exception">操作失败。</exception>
         public static Bitmap SaveDataUriAsImageFile(this string source)
         {
-            string strbase64 = source.Substring(source.IndexOf(',') + 1);
-            strbase64 = strbase64.Trim('\0');
-            Bitmap bmp2;
+            string strbase64 = source.Substring(source.IndexOf(',') + 1).Trim('\0');
             byte[] arr = Convert.FromBase64String(strbase64);
-            using (var ms = new MemoryStream(arr))
-            {
-                var bmp = new Bitmap(ms);
-                //新建第二个bitmap类型的bmp2变量。
-                bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
-                //将第一个bmp拷贝到bmp2中
-                Graphics draw = Graphics.FromImage(bmp2);
-                using (draw)
-                {
-                    draw.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
-                }
-            }
+            using var ms = new MemoryStream(arr);
+            using var bmp = new Bitmap(ms);
+            //新建第二个bitmap类型的bmp2变量。
+            using var bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
+            using var draw = Graphics.FromImage(bmp2);
+            draw.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
             return bmp2;
         }
-    } //end class
+    }
 }

+ 22 - 27
Masuit.Tools/Models/Email.cs

@@ -83,20 +83,16 @@ namespace Masuit.Tools.Models
         /// <returns></returns>
         public void SendAsync(Action<string> completedCallback)
         {
-            using (SmtpClient smtpClient = GetSmtpClient)
-            {
-                using (MailMessage mailMessage = GetClient)
-                {
-                    if (smtpClient == null || mailMessage == null) return;
-                    Subject = Subject;
-                    Body = Body;
-                    //EnableSsl = false;
-                    //发送邮件回调方法
-                    actionSendCompletedCallback = completedCallback;
-                    smtpClient.SendCompleted += SendCompletedCallback;
-                    smtpClient.SendAsync(mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-                }
-            }
+            using var smtpClient = GetSmtpClient;
+            using var mailMessage = GetClient;
+            if (smtpClient == null || mailMessage == null) return;
+            Subject = Subject;
+            Body = Body;
+            //EnableSsl = false;
+            //发送邮件回调方法
+            actionSendCompletedCallback = completedCallback;
+            smtpClient.SendCompleted += SendCompletedCallback;
+            smtpClient.SendAsync(mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
         }
 
         /// <summary>
@@ -104,17 +100,13 @@ namespace Masuit.Tools.Models
         /// </summary>
         public void Send()
         {
-            using (SmtpClient smtpClient = GetSmtpClient)
-            {
-                using (MailMessage mailMessage = GetClient)
-                {
-                    if (smtpClient == null || mailMessage == null) return;
-                    Subject = Subject;
-                    Body = Body;
-                    //EnableSsl = false;
-                    smtpClient.Send(mailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
-                }
-            }
+            using SmtpClient smtpClient = GetSmtpClient;
+            using MailMessage mailMessage = GetClient;
+            if (smtpClient == null || mailMessage == null) return;
+            Subject = Subject;
+            Body = Body;
+            //EnableSsl = false;
+            smtpClient.Send(mailMessage); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
         }
 
         /// <summary>
@@ -128,17 +120,20 @@ namespace Masuit.Tools.Models
             //写入日志
             //return;
             if (actionSendCompletedCallback == null) return;
-            string message = string.Empty;
+            string message;
             if (e.Cancelled)
             {
                 message = "异步操作取消";
             }
             else if (e.Error != null)
             {
-                message = (string.Format("UserState:{0},Message:{1}", (string)e.UserState, e.Error.ToString()));
+                message = ($"UserState:{(string)e.UserState},Message:{e.Error}");
             }
             else
+            {
                 message = (string)e.UserState;
+            }
+
             //执行回调方法
             actionSendCompletedCallback(message);
         }

+ 136 - 194
Masuit.Tools/Net/FtpClient.cs

@@ -83,55 +83,45 @@ namespace Masuit.Tools.Net
         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
         public void Download(string remoteFileName, string localFileName, bool ifCredential = false, Action<int, int> updateProgress = null)
         {
-            using (FileStream outputStream = new FileStream(localFileName, FileMode.Create))
+            using FileStream outputStream = new FileStream(localFileName, FileMode.Create);
+            if (FtpServer == null || FtpServer.Trim().Length == 0)
             {
-                if (FtpServer == null || FtpServer.Trim().Length == 0)
-                {
-                    throw new Exception("ftp下载目标服务器地址未设置!");
-                }
+                throw new Exception("ftp下载目标服务器地址未设置!");
+            }
 
-                Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
-                var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
-                ftpsize.UseBinary = true;
-                var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-                reqFtp.UseBinary = true;
-                reqFtp.KeepAlive = false;
-                if (ifCredential) //使用用户身份认证
-                {
-                    ftpsize.Credentials = new NetworkCredential(Username, Password);
-                    reqFtp.Credentials = new NetworkCredential(Username, Password);
-                }
+            Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
+            var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
+            ftpsize.UseBinary = true;
+            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
+            reqFtp.UseBinary = true;
+            reqFtp.KeepAlive = false;
+            if (ifCredential) //使用用户身份认证
+            {
+                ftpsize.Credentials = new NetworkCredential(Username, Password);
+                reqFtp.Credentials = new NetworkCredential(Username, Password);
+            }
 
-                ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
-                using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
+            ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
+            using var re = (FtpWebResponse)ftpsize.GetResponse();
+            long totalBytes = re.ContentLength;
+            reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var ftpStream = response.GetResponseStream();
+            //更新进度 
+            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
+            long totalDownloadedByte = 0;
+            int bufferSize = 1024 * 1024;
+            byte[] buffer = new byte[bufferSize];
+            if (ftpStream != null)
+            {
+                var readCount = ftpStream.Read(buffer, 0, bufferSize);
+                while (readCount > 0)
                 {
-                    long totalBytes = re.ContentLength;
-                    reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
-                    var response = (FtpWebResponse)reqFtp.GetResponse();
-                    using (response)
-                    {
-                        var ftpStream = response.GetResponseStream();
-                        //更新进度 
-                        using (ftpStream)
-                        {
-                            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
-                            long totalDownloadedByte = 0;
-                            int bufferSize = 1024 * 1024;
-                            byte[] buffer = new byte[bufferSize];
-                            if (ftpStream != null)
-                            {
-                                var readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                while (readCount > 0)
-                                {
-                                    totalDownloadedByte = readCount + totalDownloadedByte;
-                                    outputStream.Write(buffer, 0, readCount);
-                                    //更新进度 
-                                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
-                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                }
-                            }
-                        }
-                    }
+                    totalDownloadedByte = readCount + totalDownloadedByte;
+                    outputStream.Write(buffer, 0, readCount);
+                    //更新进度 
+                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
+                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                 }
             }
         }
@@ -146,54 +136,46 @@ namespace Masuit.Tools.Net
         /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
         public void BrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<int, int> updateProgress = null)
         {
-            using (FileStream outputStream = new FileStream(localFileName, FileMode.Append))
+            using var outputStream = new FileStream(localFileName, FileMode.Append);
+            if (FtpServer == null || FtpServer.Trim().Length == 0)
             {
-                if (FtpServer == null || FtpServer.Trim().Length == 0)
-                {
-                    throw new Exception("ftp下载目标服务器地址未设置!");
-                }
+                throw new Exception("ftp下载目标服务器地址未设置!");
+            }
 
-                Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
-                var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
-                ftpsize.UseBinary = true;
-                ftpsize.ContentOffset = size;
-                var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
-                reqFtp.UseBinary = true;
-                reqFtp.KeepAlive = false;
-                reqFtp.ContentOffset = size;
-                if (ifCredential) //使用用户身份认证
-                {
-                    ftpsize.Credentials = new NetworkCredential(Username, Password);
-                    reqFtp.Credentials = new NetworkCredential(Username, Password);
-                }
+            Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
+            var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
+            ftpsize.UseBinary = true;
+            ftpsize.ContentOffset = size;
+            var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
+            reqFtp.UseBinary = true;
+            reqFtp.KeepAlive = false;
+            reqFtp.ContentOffset = size;
+            if (ifCredential) //使用用户身份认证
+            {
+                ftpsize.Credentials = new NetworkCredential(Username, Password);
+                reqFtp.Credentials = new NetworkCredential(Username, Password);
+            }
 
-                ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
-                using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
+            ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
+            using FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
+            var totalBytes = re.ContentLength;
+            reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var ftpStream = response.GetResponseStream();
+            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
+            long totalDownloadedByte = 0;
+            int bufferSize = 1024 * 1024;
+            byte[] buffer = new byte[bufferSize];
+            if (ftpStream != null)
+            {
+                var readCount = ftpStream.Read(buffer, 0, bufferSize);
+                while (readCount > 0)
                 {
-                    var totalBytes = re.ContentLength;
-                    reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
-                    using (var response = (FtpWebResponse)reqFtp.GetResponse())
-                    {
-                        using (var ftpStream = response.GetResponseStream())
-                        {
-                            updateProgress?.Invoke((int)totalBytes, 0); //更新进度条 
-                            long totalDownloadedByte = 0;
-                            int bufferSize = 1024 * 1024;
-                            byte[] buffer = new byte[bufferSize];
-                            if (ftpStream != null)
-                            {
-                                var readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                while (readCount > 0)
-                                {
-                                    totalDownloadedByte = readCount + totalDownloadedByte;
-                                    outputStream.Write(buffer, 0, readCount);
-                                    //更新进度 
-                                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
-                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
-                                }
-                            }
-                        }
-                    }
+                    totalDownloadedByte = readCount + totalDownloadedByte;
+                    outputStream.Write(buffer, 0, readCount);
+                    //更新进度 
+                    updateProgress?.Invoke((int)totalBytes, (int)totalDownloadedByte); //更新进度条 
+                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                 }
             }
         }
@@ -213,10 +195,8 @@ namespace Masuit.Tools.Net
                 long size = 0;
                 if (File.Exists(localFileName))
                 {
-                    using (FileStream outputStream = new FileStream(localFileName, FileMode.Open))
-                    {
-                        size = outputStream.Length;
-                    }
+                    using var outputStream = new FileStream(localFileName, FileMode.Open);
+                    size = outputStream.Length;
                 }
 
                 BrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
@@ -252,24 +232,20 @@ namespace Masuit.Tools.Net
             reqFtp.ContentLength = finfo.Length; //为request指定上传文件的大小
             int buffLength = 1024 * 1024;
             byte[] buff = new byte[buffLength];
-            using (var fs = finfo.OpenRead())
+            using var fs = finfo.OpenRead();
+            using var stream = reqFtp.GetRequestStream();
+            var contentLen = fs.Read(buff, 0, buffLength);
+            int allbye = (int)finfo.Length;
+            //更新进度 
+            updateProgress?.Invoke(allbye, 0); //更新进度条 
+            int startbye = 0;
+            while (contentLen != 0)
             {
-                using (var stream = reqFtp.GetRequestStream())
-                {
-                    var contentLen = fs.Read(buff, 0, buffLength);
-                    int allbye = (int)finfo.Length;
-                    //更新进度 
-                    updateProgress?.Invoke(allbye, 0); //更新进度条 
-                    int startbye = 0;
-                    while (contentLen != 0)
-                    {
-                        startbye = contentLen + startbye;
-                        stream.Write(buff, 0, contentLen);
-                        //更新进度 
-                        updateProgress?.Invoke(allbye, startbye); //更新进度条 
-                        contentLen = fs.Read(buff, 0, buffLength);
-                    }
-                }
+                startbye = contentLen + startbye;
+                stream.Write(buff, 0, contentLen);
+                //更新进度 
+                updateProgress?.Invoke(allbye, startbye); //更新进度条 
+                contentLen = fs.Read(buff, 0, buffLength);
             }
         }
 
@@ -336,24 +312,20 @@ namespace Masuit.Tools.Net
             int buffLength = 1024 * 1024; // 缓冲大小设置为2kb 
             byte[] buff = new byte[buffLength];
             // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
-            using (FileStream fs = fileInf.OpenRead())
+            using FileStream fs = fileInf.OpenRead();
+            using var strm = reqFtp.GetRequestStream();
+            // 把上传的文件写入流 
+            fs.Seek(startfilesize, 0);
+            int contentLen = fs.Read(buff, 0, buffLength);
+            // 流内容没有结束 
+            while (contentLen != 0)
             {
-                using (var strm = reqFtp.GetRequestStream())
-                {
-                    // 把上传的文件写入流 
-                    fs.Seek(startfilesize, 0);
-                    int contentLen = fs.Read(buff, 0, buffLength);
-                    // 流内容没有结束 
-                    while (contentLen != 0)
-                    {
-                        // 把内容从file stream 写入 upload stream 
-                        strm.Write(buff, 0, contentLen);
-                        contentLen = fs.Read(buff, 0, buffLength);
-                        startbye += contentLen;
-                        //更新进度 
-                        updateProgress?.Invoke((int)allbye, (int)startbye); //更新进度条 
-                    }
-                }
+                // 把内容从file stream 写入 upload stream 
+                strm.Write(buff, 0, contentLen);
+                contentLen = fs.Read(buff, 0, buffLength);
+                startbye += contentLen;
+                //更新进度 
+                updateProgress?.Invoke((int)allbye, (int)startbye); //更新进度条 
             }
 
             return true;
@@ -406,7 +378,7 @@ namespace Masuit.Tools.Net
                 reqFtp.UseBinary = true;
                 reqFtp.Credentials = new NetworkCredential(Username, Password); //用户,密码
                 reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
-                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
+                var response = (FtpWebResponse)reqFtp.GetResponse();
                 var filesize = response.ContentLength;
                 return filesize;
             }
@@ -426,21 +398,17 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public List<string> GetFilesDetails(string relativePath = "")
         {
-            List<string> result = new List<string>();
+            var result = new List<string>();
             var ftp = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine("ftp://" + FtpServer, relativePath).Replace("\\", "/")));
             ftp.Credentials = new NetworkCredential(Username, Password);
             ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
-            using (WebResponse response = ftp.GetResponse())
+            using var response = ftp.GetResponse();
+            using var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
+            string line = reader.ReadLine();
+            while (line != null)
             {
-                using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8))
-                {
-                    string line = reader.ReadLine();
-                    while (line != null)
-                    {
-                        result.Add(line);
-                        line = reader.ReadLine();
-                    }
-                }
+                result.Add(line);
+                line = reader.ReadLine();
             }
 
             return result;
@@ -457,29 +425,25 @@ namespace Masuit.Tools.Net
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
             reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
-            using (WebResponse response = reqFtp.GetResponse())
+            using var response = reqFtp.GetResponse();
+            using var reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
+            string line = reader.ReadLine();
+            while (line != null)
             {
-                using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8))
+                if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
                 {
-                    string line = reader.ReadLine();
-                    while (line != null)
+                    string temp = mask.Substring(0, mask.IndexOf("*", StringComparison.Ordinal));
+                    if (line.Substring(0, temp.Length) == temp)
                     {
-                        if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
-                        {
-                            string temp = mask.Substring(0, mask.IndexOf("*", StringComparison.Ordinal));
-                            if (line.Substring(0, temp.Length) == temp)
-                            {
-                                result.Add(line);
-                            }
-                        }
-                        else
-                        {
-                            result.Add(line);
-                        }
-
-                        line = reader.ReadLine();
+                        result.Add(line);
                     }
                 }
+                else
+                {
+                    result.Add(line);
+                }
+
+                line = reader.ReadLine();
             }
 
             return result;
@@ -536,16 +500,10 @@ namespace Masuit.Tools.Net
             reqFtp.KeepAlive = false;
             reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
 
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (Stream datastream = response.GetResponseStream())
-                {
-                    using (StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException()))
-                    {
-                        sr.ReadToEnd();
-                    }
-                }
-            }
+            using FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
+            using Stream datastream = response.GetResponseStream();
+            using StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException());
+            sr.ReadToEnd();
         }
 
         /// <summary>
@@ -559,16 +517,10 @@ namespace Masuit.Tools.Net
             reqFtp.Credentials = new NetworkCredential(Username, Password);
             reqFtp.KeepAlive = false;
             reqFtp.Method = WebRequestMethods.Ftp.RemoveDirectory;
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (Stream datastream = response.GetResponseStream())
-                {
-                    using (StreamReader sr = new StreamReader(datastream ?? throw new InvalidOperationException()))
-                    {
-                        sr.ReadToEnd();
-                    }
-                }
-            }
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var datastream = response.GetResponseStream();
+            using var sr = new StreamReader(datastream ?? throw new InvalidOperationException());
+            sr.ReadToEnd();
         }
 
         #endregion
@@ -586,11 +538,9 @@ namespace Masuit.Tools.Net
             reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                var fileSize = response.ContentLength;
-                return fileSize;
-            }
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            var fileSize = response.ContentLength;
+            return fileSize;
         }
 
         /// <summary>
@@ -648,12 +598,8 @@ namespace Masuit.Tools.Net
             reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (response.GetResponseStream())
-                {
-                }
-            }
+            using var response = (FtpWebResponse)reqFtp.GetResponse();
+            using var _ = response.GetResponseStream();
         }
 
         /// <summary>
@@ -669,12 +615,8 @@ namespace Masuit.Tools.Net
             reqFtp.RenameTo = newFilename;
             reqFtp.UseBinary = true;
             reqFtp.Credentials = new NetworkCredential(Username, Password);
-            using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
-            {
-                using (response.GetResponseStream())
-                {
-                }
-            }
+            using FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
+            using var _ = response.GetResponseStream();
         }
 
         /// <summary>

+ 24 - 33
Masuit.Tools/Net/MultiThreadDownloader.cs

@@ -233,31 +233,27 @@ namespace Masuit.Tools.Net
         void MergeParts()
         {
             List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
-            using (var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
+            using var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite);
+            long totalBytesWritten = 0;
+            int mergeProgress = 0;
+            foreach (var item in mergeOrderedList)
             {
-                long totalBytesWritten = 0;
-                int mergeProgress = 0;
-                foreach (var item in mergeOrderedList)
+                using var pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read);
+                byte[] buffer = new byte[4096];
+                int read;
+                while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
                 {
-                    using (FileStream pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read))
+                    fs.Write(buffer, 0, read);
+                    totalBytesWritten += read;
+                    int temp = (int)(totalBytesWritten * 1d / Size * 100);
+                    if (temp != mergeProgress && FileMergeProgressChanged != null)
                     {
-                        byte[] buffer = new byte[4096];
-                        int read;
-                        while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
-                        {
-                            fs.Write(buffer, 0, read);
-                            totalBytesWritten += read;
-                            int temp = (int)(totalBytesWritten * 1d / Size * 100);
-                            if (temp != mergeProgress && FileMergeProgressChanged != null)
-                            {
-                                mergeProgress = temp;
-                                _aop.Post(state => FileMergeProgressChanged(this, temp), null);
-                            }
-                        }
+                        mergeProgress = temp;
+                        _aop.Post(state => FileMergeProgressChanged(this, temp), null);
                     }
-
-                    File.Delete(item.FullPath);
                 }
+
+                File.Delete(item.FullPath);
             }
         }
 
@@ -338,22 +334,17 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static long GetContentLength(string url, ref bool rangeAllowed, ref string redirectedUrl)
         {
-            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
+            var req = WebRequest.Create(url) as HttpWebRequest;
             req.UserAgent = "Mozilla/4.0 (compatible; MSIE 11.0; Windows NT 6.2; .NET CLR 1.0.3705;)";
             req.ServicePoint.ConnectionLimit = 4;
-            long ctl;
-            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
+            using var resp = req.GetResponse() as HttpWebResponse;
+            redirectedUrl = resp.ResponseUri.OriginalString;
+            var ctl = resp.ContentLength;
+            rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
             {
-                redirectedUrl = resp.ResponseUri.OriginalString;
-                ctl = resp.ContentLength;
-                rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
-                {
-                    HeaderName = v,
-                    HeaderValue = resp.Headers[i]
-                }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
-                resp.Close();
-            }
-
+                HeaderName = v,
+                HeaderValue = resp.Headers[i]
+            }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
             req.Abort();
             return ctl;
         }

+ 93 - 84
Masuit.Tools/Net/SocketClient.cs

@@ -232,7 +232,7 @@ namespace Masuit.Tools.Net
             }
 
             stream.Seek(0, SeekOrigin.Begin); //必须要这个 或者stream.Position = 0;
-            T t = (T) format.Deserialize(stream);
+            T t = (T)format.Deserialize(stream);
             stream.Close();
             return t;
         }
@@ -248,51 +248,57 @@ namespace Masuit.Tools.Net
         /// <param name="progress">处理过程</param>
         public static bool ReceiveFile(this Socket socket, string path, string filename, long size, Action<int> progress)
         {
+            if (!Directory.Exists(path))
+            {
+                return false;
+            }
+
+            //主要是防止有重名文件
+            string savepath = GetPath(path, filename); //得到文件路径
+            //缓冲区
+            byte[] file = new byte[m_maxpacket];
+            int receivedata = m_maxpacket; //每次要接收的长度
+            long offset = 0; //循环接收的总长度
+            long lastdata = size; //剩余多少还没接收
+            int mark = 0;
+            using var fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write);
+            if (size <= 0)
+            {
+                return false;
+            }
+
             bool ret = false;
-            if (Directory.Exists(path))
+            while (true)
             {
-                //主要是防止有重名文件
-                string savepath = GetPath(path, filename); //得到文件路径
-                //缓冲区
-                byte[] file = new byte[m_maxpacket];
-                int receivedata = m_maxpacket; //每次要接收的长度
-                long offset = 0; //循环接收的总长度
-                long lastdata = size; //剩余多少还没接收
-                int mark = 0;
-                using (FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write))
+                if (lastdata < receivedata)
                 {
-                    if (size > 0)
-                        while (true)
-                        {
-                            if (lastdata < receivedata)
-                                receivedata = Convert.ToInt32(lastdata);
-                            var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
-                            if (count > 0)
-                            {
-                                fs.Write(file, 0, count);
-                                offset += count;
-                                lastdata -= count;
-                                mark = 0;
-                            }
-                            else
-                            {
-                                mark++; //连续5次接收为0字节 则跳出循环
-                                if (mark == 10)
-                                    break;
-                            }
-
-                            //接收进度
-                            if (progress != null)
-                                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
-                            //接收完毕
-                            if (offset == size)
-                            {
-                                ret = true;
-                                break;
-                            }
-                        }
-
-                    fs.Close();
+                    receivedata = Convert.ToInt32(lastdata);
+                }
+
+                var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
+                if (count > 0)
+                {
+                    fs.Write(file, 0, count);
+                    offset += count;
+                    lastdata -= count;
+                    mark = 0;
+                }
+                else
+                {
+                    mark++; //连续5次接收为0字节 则跳出循环
+                    if (mark == 10)
+                    {
+                        break;
+                    }
+                }
+
+                //接收进度
+                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
+                //接收完毕
+                if (offset == size)
+                {
+                    ret = true;
+                    break;
                 }
             }
 
@@ -467,50 +473,55 @@ namespace Masuit.Tools.Net
         /// <returns>处理结果</returns>
         public static bool SendFile(this Socket socket, string path, bool issend, Action<int> progress)
         {
-            bool ret = false;
-            if (File.Exists(path))
+            if (!File.Exists(path))
+            {
+                return false;
+            }
+
+            var fileinfo = new FileInfo(path);
+            string filename = fileinfo.Name;
+            long length = fileinfo.Length;
+            //发送文件信息
+            if (issend)
             {
-                FileInfo fileinfo = new FileInfo(path);
-                string filename = fileinfo.Name;
-                long length = fileinfo.Length;
-                //发送文件信息
-                if (issend)
-                    SendVarData(socket, filename + "|" + length);
-                //发送文件
-                long offset = 0;
-                byte[] b = new byte[m_maxpacket];
-                int mark = 0;
-                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
+                SendVarData(socket, filename + "|" + length);
+            }
+
+            //发送文件
+            long offset = 0;
+            byte[] b = new byte[m_maxpacket];
+            int mark = 0;
+            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
+            int senddata = b.Length;
+            //循环读取发送
+            while (true)
+            {
+                int count = fs.Read(b, 0, senddata);
+                if (count > 0)
+                {
+                    socket.Send(b, 0, count, SocketFlags.None);
+                    offset += count;
+                    mark = 0;
+                }
+                else
                 {
-                    int senddata = b.Length;
-                    long i = length;
-                    //循环读取发送
-                    while (true)
+                    mark++;
+                    if (mark == 10)
                     {
-                        int count = fs.Read(b, 0, senddata);
-                        if (count > 0)
-                        {
-                            socket.Send(b, 0, count, SocketFlags.None);
-                            offset += count;
-                            mark = 0;
-                        }
-                        else
-                        {
-                            mark++;
-                            if (mark == 10)
-                                break;
-                        }
-
-                        if (progress != null)
-                            progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
-                        if (offset == length)
-                            break;
-                        Thread.Sleep(50); //设置等待时间,以免粘包
+                        break;
                     }
                 }
+
+                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
+                if (offset == length)
+                {
+                    return true;
+                }
+
+                Thread.Sleep(50); //设置等待时间,以免粘包
             }
 
-            return ret;
+            return false;
         }
 
         /// <summary>
@@ -539,11 +550,9 @@ namespace Masuit.Tools.Net
         private static byte[] SerializeObject(object obj)
         {
             IFormatter format = new BinaryFormatter();
-            MemoryStream stream = new MemoryStream();
+            using var stream = new MemoryStream();
             format.Serialize(stream, obj);
-            byte[] ret = stream.ToArray();
-            stream.Close();
-            return ret;
+            return stream.ToArray();
         }
 
         private static string GetSendPacketLengthStr(int size)

+ 168 - 201
Masuit.Tools/Net/WebExtension.cs

@@ -1,4 +1,9 @@
-using System;
+using Masuit.Tools.Logging;
+using Masuit.Tools.Models;
+using Masuit.Tools.NoSQL;
+using Masuit.Tools.Security;
+using Newtonsoft.Json;
+using System;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Linq;
@@ -7,11 +12,6 @@ using System.Runtime.Remoting.Messaging;
 using System.Threading.Tasks;
 using System.Web;
 using System.Web.SessionState;
-using Masuit.Tools.Logging;
-using Masuit.Tools.Models;
-using Masuit.Tools.NoSQL;
-using Masuit.Tools.Security;
-using Newtonsoft.Json;
 
 namespace Masuit.Tools.Net
 {
@@ -36,7 +36,7 @@ namespace Masuit.Tools.Net
                 CallContext.SetData("db", db);
             }
 
-            db = (T) CallContext.GetData("db");
+            db = (T)CallContext.GetData("db");
             return db;
         }
 
@@ -140,10 +140,8 @@ namespace Masuit.Tools.Net
 
             try
             {
-                using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                {
-                    redisHelper.SetHash("Session:" + sessionKey, key, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
-                }
+                using var redisHelper = RedisHelper.GetInstance(1);
+                redisHelper.SetHash("Session:" + sessionKey, key, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
             }
             catch
             {
@@ -162,7 +160,7 @@ namespace Masuit.Tools.Net
         /// <param name="session"></param>
         /// <param name="key">键</param>
         /// <returns>对象</returns>
-        public static T Get<T>(this HttpSessionStateBase session, string key) => (T) session[key];
+        public static T Get<T>(this HttpSessionStateBase session, string key) => (T)session[key];
 
         /// <summary>
         /// 获取Session
@@ -171,7 +169,7 @@ namespace Masuit.Tools.Net
         /// <param name="session"></param>
         /// <param name="key">键</param>
         /// <returns>对象</returns>
-        public static T Get<T>(this HttpSessionState session, string key) => (T) session[key];
+        public static T Get<T>(this HttpSessionState session, string key) => (T)session[key];
 
         /// <summary>
         /// 从Redis取Session
@@ -189,40 +187,29 @@ namespace Masuit.Tools.Net
             }
 
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
-            if (!string.IsNullOrEmpty(sessionKey))
+            if (string.IsNullOrEmpty(sessionKey))
             {
-                T obj = default(T);
-                if (_ != default(T))
-                {
-                    obj = _.Get<T>(key);
-                }
+                return default(T);
+            }
 
-                if (obj == default(T))
-                {
-                    try
-                    {
-                        sessionKey = "Session:" + sessionKey;
-                        using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                        {
-                            if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
-                            {
-                                redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
-                                return redisHelper.GetHash<T>(sessionKey, key);
-                            }
+            T obj = _.Get<T>(key);
 
-                            return default(T);
-                        }
-                    }
-                    catch
-                    {
-                        return default(T);
-                    }
+            try
+            {
+                sessionKey = "Session:" + sessionKey;
+                using var redisHelper = RedisHelper.GetInstance(1);
+                if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
+                {
+                    redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
+                    return redisHelper.GetHash<T>(sessionKey, key);
                 }
 
-                return obj;
+                return default(T);
+            }
+            catch
+            {
+                return default(T);
             }
-
-            return default(T);
         }
 
         /// <summary>
@@ -241,40 +228,33 @@ namespace Masuit.Tools.Net
             }
 
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
-            if (!string.IsNullOrEmpty(sessionKey))
+            if (string.IsNullOrEmpty(sessionKey))
             {
-                T obj = default(T);
-                if (_ != default(T))
-                {
-                    obj = _.Get<T>(key);
-                }
+                return default(T);
+            }
 
-                if (obj == null)
-                {
-                    try
-                    {
-                        sessionKey = "Session:" + sessionKey;
-                        using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                        {
-                            if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
-                            {
-                                redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
-                                return redisHelper.GetHash<T>(sessionKey, key);
-                            }
+            T obj = _.Get<T>(key);
+            if (obj != null)
+            {
+                return obj;
+            }
 
-                            return default(T);
-                        }
-                    }
-                    catch
-                    {
-                        return default(T);
-                    }
+            try
+            {
+                sessionKey = "Session:" + sessionKey;
+                using RedisHelper redisHelper = RedisHelper.GetInstance(1);
+                if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
+                {
+                    redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
+                    return redisHelper.GetHash<T>(sessionKey, key);
                 }
 
-                return obj;
+                return default(T);
+            }
+            catch
+            {
+                return default(T);
             }
-
-            return default(T);
         }
 
         /// <summary>
@@ -291,29 +271,25 @@ namespace Masuit.Tools.Net
             }
 
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
-            if (!string.IsNullOrEmpty(sessionKey))
+            if (string.IsNullOrEmpty(sessionKey))
             {
-                if (_ != null)
-                {
-                    _[key] = null;
-                }
+                return;
+            }
 
-                try
-                {
-                    sessionKey = "Session:" + sessionKey;
-                    using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                    {
-                        if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
-                        {
-                            redisHelper.DeleteHash(sessionKey, key);
-                        }
-                    }
-                }
-                catch (Exception e)
+            try
+            {
+                _[key] = null;
+                sessionKey = "Session:" + sessionKey;
+                using var redisHelper = RedisHelper.GetInstance(1);
+                if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
                 {
-                    LogManager.Error(e);
+                    redisHelper.DeleteHash(sessionKey, key);
                 }
             }
+            catch (Exception e)
+            {
+                LogManager.Error(e);
+            }
         }
 
         /// <summary>
@@ -330,29 +306,25 @@ namespace Masuit.Tools.Net
             }
 
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
-            if (!string.IsNullOrEmpty(sessionKey))
+            if (string.IsNullOrEmpty(sessionKey))
             {
-                if (_ != null)
-                {
-                    _[key] = null;
-                }
+                return;
+            }
 
-                try
-                {
-                    sessionKey = "Session:" + sessionKey;
-                    using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                    {
-                        if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
-                        {
-                            redisHelper.DeleteHash(sessionKey, key);
-                        }
-                    }
-                }
-                catch (Exception e)
+            _[key] = null;
+            try
+            {
+                sessionKey = "Session:" + sessionKey;
+                using RedisHelper redisHelper = RedisHelper.GetInstance(1);
+                if (redisHelper.KeyExists(sessionKey) && redisHelper.HashExists(sessionKey, key))
                 {
-                    LogManager.Error(e);
+                    redisHelper.DeleteHash(sessionKey, key);
                 }
             }
+            catch (Exception e)
+            {
+                LogManager.Error(e);
+            }
         }
 
         /// <summary>
@@ -364,10 +336,8 @@ namespace Masuit.Tools.Net
         {
             try
             {
-                using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                {
-                    return redisHelper.GetServer().Keys(1, "Session:*").Count();
-                }
+                using RedisHelper redisHelper = RedisHelper.GetInstance(1);
+                return redisHelper.GetServer().Keys(1, "Session:*").Count();
             }
             catch (Exception e)
             {
@@ -385,10 +355,8 @@ namespace Masuit.Tools.Net
         {
             try
             {
-                using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
-                {
-                    return redisHelper.GetServer().Keys(1, "Session:*").Count();
-                }
+                using RedisHelper redisHelper = RedisHelper.GetInstance(1);
+                return redisHelper.GetServer().Keys(1, "Session:*").Count();
             }
             catch (Exception e)
             {
@@ -432,91 +400,91 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static async Task<PhysicsAddress> GetPhysicsAddressInfo(this string ip)
         {
-            ip.MatchInetAddress(out var isIpAddress);
-            if (isIpAddress)
+            if (!ip.MatchInetAddress())
+            {
+                return null;
+            }
+
+            string ak = ConfigurationManager.AppSettings["BaiduAK"];
+            if (string.IsNullOrEmpty(ak))
+            {
+                throw new Exception("未配置BaiduAK,请先在您的应用程序web.config或者App.config中的AppSettings节点下添加BaiduAK配置节(注意大小写)");
+            }
+
+            using var client = new HttpClient()
+            {
+                BaseAddress = new Uri("http://api.map.baidu.com")
+            };
+            client.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
+            var task = client.GetAsync($"/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
             {
-                string ak = ConfigurationManager.AppSettings["BaiduAK"];
-                if (string.IsNullOrEmpty(ak))
+                if (t.IsFaulted || t.IsCanceled)
                 {
-                    throw new Exception("未配置BaiduAK,请先在您的应用程序web.config或者App.config中的AppSettings节点下添加BaiduAK配置节(注意大小写)");
+                    return null;
                 }
 
-                using (HttpClient client = new HttpClient()
+                var res = await t;
+                if (!res.IsSuccessStatusCode)
                 {
-                    BaseAddress = new Uri("http://api.map.baidu.com")
-                })
+                    return null;
+                }
+
+                var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
+                if (ipAddress.Status == 0)
                 {
-                    client.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
-                    var task = client.GetAsync($"/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
+                    LatiLongitude point = ipAddress.AddressInfo.LatiLongitude;
+                    var result = client.GetStringAsync($"/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
+                    var address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
+                    if (address.Status == 0)
                     {
-                        if (t.IsFaulted || t.IsCanceled)
+                        return address;
+                    }
+                }
+                else
+                {
+                    using var client2 = new HttpClient
+                    {
+                        BaseAddress = new Uri("http://ip.taobao.com")
+                    };
+                    return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
+                    {
+                        if (tt.IsFaulted || tt.IsCanceled)
                         {
                             return null;
                         }
 
-                        var res = await t;
-                        if (res.IsSuccessStatusCode)
+                        var result = await tt;
+                        if (!result.IsSuccessStatusCode)
                         {
-                            var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
-                            if (ipAddress.Status == 0)
-                            {
-                                LatiLongitude point = ipAddress.AddressInfo.LatiLongitude;
-                                string result = client.GetStringAsync($"/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
-                                PhysicsAddress address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
-                                if (address.Status == 0)
-                                {
-                                    return address;
-                                }
-                            }
-                            else
+                            return null;
+                        }
+
+                        var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
+                        if (taobaoIp.Code == 0)
+                        {
+                            return new PhysicsAddress()
                             {
-                                using (var client2 = new HttpClient
-                                {
-                                    BaseAddress = new Uri("http://ip.taobao.com")
-                                })
+                                Status = 0,
+                                AddressResult = new AddressResult()
                                 {
-                                    return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
+                                    FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
+                                    AddressComponent = new AddressComponent()
                                     {
-                                        if (tt.IsFaulted || tt.IsCanceled)
-                                        {
-                                            return null;
-                                        }
-
-                                        var result = await tt;
-                                        if (result.IsSuccessStatusCode)
-                                        {
-                                            TaobaoIP taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                                            if (taobaoIp.Code == 0)
-                                            {
-                                                return new PhysicsAddress()
-                                                {
-                                                    Status = 0,
-                                                    AddressResult = new AddressResult()
-                                                    {
-                                                        FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
-                                                        AddressComponent = new AddressComponent()
-                                                        {
-                                                            Province = taobaoIp.IpData.Region
-                                                        },
-                                                        Pois = new List<Pois>()
-                                                    }
-                                                };
-                                            }
-                                        }
-
-                                        return null;
-                                    });
+                                        Province = taobaoIp.IpData.Region
+                                    },
+                                    Pois = new List<Pois>()
                                 }
-                            }
+                            };
                         }
 
                         return null;
                     });
-                    return await await task;
                 }
-            }
 
-            return null;
+                return null;
+            });
+            return await await task;
+
         }
 
         /// <summary>
@@ -526,37 +494,36 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static string GetISP(this string ip)
         {
-            if (ip.MatchInetAddress())
+            if (!ip.MatchInetAddress())
             {
-                using (var client = new HttpClient
+                return $"{ip}不是一个合法的IP";
+            }
+
+            using var client = new HttpClient
+            {
+                BaseAddress = new Uri("http://ip.taobao.com")
+            };
+            var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
+            {
+                if (t.IsFaulted)
                 {
-                    BaseAddress = new Uri("http://ip.taobao.com")
-                })
+                    return $"未能找到{ip}的ISP信息";
+                }
+
+                var result = await t;
+                if (result.IsSuccessStatusCode)
                 {
-                    var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
+                    var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
+                    if (taobaoIp.Code == 0)
                     {
-                        if (t.IsFaulted)
-                        {
-                            return $"未能找到{ip}的ISP信息";
-                        }
-
-                        var result = await t;
-                        if (result.IsSuccessStatusCode)
-                        {
-                            TaobaoIP taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                            if (taobaoIp.Code == 0)
-                            {
-                                return taobaoIp.IpData.Isp;
-                            }
-                        }
-
-                        return $"未能找到{ip}的ISP信息";
-                    });
-                    return task.Result.Result;
+                        return taobaoIp.IpData.Isp;
+                    }
                 }
-            }
 
-            return $"{ip}不是一个合法的IP";
+                return $"未能找到{ip}的ISP信息";
+            });
+            return task.Result.Result;
+
         }
 
         #endregion

+ 116 - 174
Masuit.Tools/Security/Encrypt.cs

@@ -104,23 +104,18 @@ namespace Masuit.Tools.Security
                 0xEF
             };
             var byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
-            using (fin)
+            using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
+            fout.SetLength(0);
+            byte[] bin = new byte[100];
+            long rdlen = 0;
+            long totlen = fin.Length;
+            DES des = new DESCryptoServiceProvider();
+            var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
+            while (rdlen < totlen)
             {
-                using (FileStream fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write))
-                {
-                    fout.SetLength(0);
-                    byte[] bin = new byte[100];
-                    long rdlen = 0;
-                    long totlen = fin.Length;
-                    DES des = new DESCryptoServiceProvider();
-                    var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
-                    while (rdlen < totlen)
-                    {
-                        var len = fin.Read(bin, 0, 100);
-                        encStream.Write(bin, 0, len);
-                        rdlen += len;
-                    }
-                }
+                var len = fin.Read(bin, 0, 100);
+                encStream.Write(bin, 0, len);
+                rdlen += len;
             }
         }
 
@@ -144,23 +139,18 @@ namespace Masuit.Tools.Security
                 0xEF
             };
             var byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
-            using (fin)
+            using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
+            fout.SetLength(0);
+            byte[] bin = new byte[100];
+            long rdlen = 0;
+            long totlen = fin.Length;
+            DES des = new DESCryptoServiceProvider();
+            var encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
+            while (rdlen < totlen)
             {
-                using (FileStream fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write))
-                {
-                    fout.SetLength(0);
-                    byte[] bin = new byte[100];
-                    long rdlen = 0;
-                    long totlen = fin.Length;
-                    DES des = new DESCryptoServiceProvider();
-                    CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
-                    while (rdlen < totlen)
-                    {
-                        var len = fin.Read(bin, 0, 100);
-                        encStream.Write(bin, 0, len);
-                        rdlen += len;
-                    }
-                }
+                var len = fin.Read(bin, 0, 100);
+                encStream.Write(bin, 0, len);
+                rdlen += len;
             }
         }
 
@@ -421,7 +411,7 @@ namespace Masuit.Tools.Security
                 Key = Encoding.UTF8.GetBytes(decryptKey),
                 IV = Keys
             };
-            ICryptoTransform decrypto = rijndaelProvider.CreateDecryptor();
+            var decrypto = rijndaelProvider.CreateDecryptor();
             return new CryptoStream(fs, decrypto, CryptoStreamMode.Read);
         }
 
@@ -432,13 +422,11 @@ namespace Masuit.Tools.Security
         /// <param name="outputPath">输出文件路径</param>
         public static void AESEncryptFile(this FileStream input, string outputPath)
         {
-            using (FileStream fren = new FileStream(outputPath, FileMode.Create))
-            {
-                CryptoStream enfr = AESEncryptStrream(fren, Default_AES_Key);
-                byte[] bytearrayinput = new byte[input.Length];
-                input.Read(bytearrayinput, 0, bytearrayinput.Length);
-                enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
-            }
+            using var fren = new FileStream(outputPath, FileMode.Create);
+            var enfr = AESEncryptStrream(fren, Default_AES_Key);
+            byte[] bytearrayinput = new byte[input.Length];
+            input.Read(bytearrayinput, 0, bytearrayinput.Length);
+            enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
         }
 
         /// <summary>
@@ -1214,26 +1202,17 @@ namespace Masuit.Tools.Security
         /// <param name="toEncryptText">要加密的文本数据</param>
         /// <param name="filePath">要保存的文件</param>
         /// <returns>是否加密成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath)
+        public static void EncryptToFile(this string toEncryptText, string filePath)
         {
-            bool r;
-            using (var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true))
-            {
-                using (var encryptor = _rc2Csp.CreateEncryptor(_key, _iv))
-                {
-                    var msEncrypt = new MemoryStream();
-                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = _textConverter.GetBytes(toEncryptText);
-                        csEncrypt.Write(tmp, 0, tmp.Length);
-                        csEncrypt.FlushFinalBlock();
-                    }
-                    var encrypted = msEncrypt.ToArray();
-                    tmpFileStream.Write(encrypted, 0, encrypted.Length);
-                    r = true;
-                }
-            }
-            return r;
+            using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
+            using var encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
+            var msEncrypt = new MemoryStream();
+            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
+            var tmp = _textConverter.GetBytes(toEncryptText);
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            csEncrypt.FlushFinalBlock();
+            var encrypted = msEncrypt.ToArray();
+            tmpFileStream.Write(encrypted, 0, encrypted.Length);
         }
 
         #endregion
@@ -1247,26 +1226,17 @@ namespace Masuit.Tools.Security
         /// <returns>解密后的文本</returns>
         public static string DecryptFromFile(this string filePath)
         {
-            using (var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
-            {
-                using (var decryptor = _rc2Csp.CreateDecryptor(_key, _iv))
-                {
-                    var msDecrypt = new MemoryStream();
-                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = new byte[tmpFileStream.Length];
-                        tmpFileStream.Read(tmp, 0, tmp.Length);
-                        csDecrypt.Write(tmp, 0, tmp.Length);
-                        csDecrypt.FlushFinalBlock();
-                    }
-
-                    var decrypted = msDecrypt.ToArray();
-                    var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-                    return r;
-                }
-
-            }
-
+            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
+            using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
+            var msDecrypt = new MemoryStream();
+            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
+            var tmp = new byte[tmpFileStream.Length];
+            tmpFileStream.Read(tmp, 0, tmp.Length);
+            csDecrypt.Write(tmp, 0, tmp.Length);
+            csDecrypt.FlushFinalBlock();
+            var decrypted = msDecrypt.ToArray();
+            var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
+            return r;
         }
 
         #endregion
@@ -1284,54 +1254,50 @@ namespace Masuit.Tools.Security
         /// <param name="IV">初始化向量</param>
         /// <param name="Key">加密密匙</param>
         /// <returns>是否操作成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
+        public static void EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
         {
-            var r = false;
             if ((dataIndex > 10) && (dataIndex < 1))
             {
-                return r;
+                return;
             }
             //打开要写入的文件,主要是为了保持原文件的内容不丢失
-            var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
-
+            using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
             var index = new byte[10261];
             //将读取的内容写到byte数组
-            tmpFileStream.Read(index, 0, 10261);
-            tmpFileStream.Close();
+            fs.Read(index, 0, 10261);
+
             //定义基本的加密转换运算
-            using (var encryptor = _rc2Csp.CreateEncryptor(Key, IV))
+            using var encryptor = _rc2Csp.CreateEncryptor(Key, IV);
+            var msEncrypt = new MemoryStream();
+            //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
+            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
+            var tmp = _textConverter.GetBytes(toEncryptText);
+            //将tmp输入csEncrypt,将通过Encryptor来加密。
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            //输出到msEnctypt
+            csEncrypt.FlushFinalBlock();
+
+            //将流转成byte[]
+            var encrypted = msEncrypt.ToArray();
+            if (encrypted.Length > 1024)
             {
-                var msEncrypt = new MemoryStream();
-                //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
-                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
-                {
-                    var tmp = _textConverter.GetBytes(toEncryptText);
-                    //将tmp输入csEncrypt,将通过Encryptor来加密。
-                    csEncrypt.Write(tmp, 0, tmp.Length);
-                    //输出到msEnctypt
-                    csEncrypt.FlushFinalBlock();
-                }
+                return;
+            }
 
-                //将流转成byte[]
-                var encrypted = msEncrypt.ToArray();
-                if (encrypted.Length > 1024)
-                    return false;
-                //得到加密后数据的大小,将结果存在指定的位置。
-                index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
-                index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
-                //将加密后的结果写入index(覆盖)
-                for (var i = 0; i < encrypted.Length; i++)
-                    index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
-                //建立文件流
-                tmpFileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
-                //写文件
-                tmpFileStream.Write(index, 0, 10261);
-                tmpFileStream.Flush();
-                r = true;
-                tmpFileStream.Close();
-                return r;
+            //得到加密后数据的大小,将结果存在指定的位置。
+            index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
+            index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
+            //将加密后的结果写入index(覆盖)
+            for (int i = 0; i < encrypted.Length; i++)
+            {
+                index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
             }
 
+            //建立文件流
+            using var newStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
+            newStream.Write(index, 0, 10261);
+            newStream.Flush();
+            newStream.Close();
         }
 
         #endregion
@@ -1348,35 +1314,26 @@ namespace Masuit.Tools.Security
         /// <returns>解密后的文本</returns>
         public static string DecryptFromFile(this string filePath, int dataIndex, byte[] iv, byte[] key)
         {
-            var r = "";
             if ((dataIndex > 10) && (dataIndex < 1))
             {
-                return r;
+                return "";
             }
 
-            using (var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
-            {
-                using (var decryptor = _rc2Csp.CreateDecryptor(key, iv))
-                {
-                    var msDecrypt = new MemoryStream();
-                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
-                    {
-                        var index = new byte[10261];
-
-                        tmpFileStream.Read(index, 0, 10261);
-                        var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
-                        var tmp = new byte[count];
+            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
+            using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
+            var msDecrypt = new MemoryStream();
+            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
+            var index = new byte[10261];
 
-                        Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
-                        csDecrypt.Write(tmp, 0, count);
-                        csDecrypt.FlushFinalBlock();
-                        var decrypted = msDecrypt.ToArray();
-                        r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-                    }
-                }
-            }
+            tmpFileStream.Read(index, 0, 10261);
+            var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
+            var tmp = new byte[count];
 
-            return r;
+            Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
+            csDecrypt.Write(tmp, 0, count);
+            csDecrypt.FlushFinalBlock();
+            var decrypted = msDecrypt.ToArray();
+            return _textConverter.GetString(decrypted, 0, decrypted.Length);
         }
 
         #endregion
@@ -1391,26 +1348,18 @@ namespace Masuit.Tools.Security
         /// <param name="iv">初始化向量</param>
         /// <param name="key">加密密匙</param>
         /// <returns>是否加密成功</returns>
-        public static bool EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
+        public static void EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
         {
-            using (var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true))
-            {
-                using (var encryptor = _rc2Csp.CreateEncryptor(key, iv))
-                {
-                    var msEncrypt = new MemoryStream();
-                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = _textConverter.GetBytes(toEncryptText);
-                        csEncrypt.Write(tmp, 0, tmp.Length);
-                        csEncrypt.FlushFinalBlock();
-                        var encrypted = msEncrypt.ToArray();
-                        tmpFileStream.Write(encrypted, 0, encrypted.Length);
-                        tmpFileStream.Flush();
-                        var r = true;
-                        return r;
-                    }
-                }
-            }
+            using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
+            using var encryptor = _rc2Csp.CreateEncryptor(key, iv);
+            var msEncrypt = new MemoryStream();
+            using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
+            var tmp = _textConverter.GetBytes(toEncryptText);
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            csEncrypt.FlushFinalBlock();
+            var encrypted = msEncrypt.ToArray();
+            tmpFileStream.Write(encrypted, 0, encrypted.Length);
+            tmpFileStream.Flush();
         }
 
         #endregion
@@ -1426,23 +1375,16 @@ namespace Masuit.Tools.Security
         /// <returns>解密后的文本</returns>
         public static string DecryptFromFile(this string filePath, byte[] iv, byte[] key)
         {
-            using (var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
-            {
-                using (var decryptor = _rc2Csp.CreateDecryptor(key, iv))
-                {
-                    var msDecrypt = new MemoryStream();
-                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
-                    {
-                        var tmp = new byte[tmpFileStream.Length];
-                        tmpFileStream.Read(tmp, 0, tmp.Length);
-                        csDecrypt.Write(tmp, 0, tmp.Length);
-                        csDecrypt.FlushFinalBlock();
-                        var decrypted = msDecrypt.ToArray();
-                        var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
-                        return r;
-                    }
-                }
-            }
+            using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
+            using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
+            var msDecrypt = new MemoryStream();
+            using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
+            var tmp = new byte[tmpFileStream.Length];
+            tmpFileStream.Read(tmp, 0, tmp.Length);
+            csDecrypt.Write(tmp, 0, tmp.Length);
+            csDecrypt.FlushFinalBlock();
+            var decrypted = msDecrypt.ToArray();
+            return _textConverter.GetString(decrypted, 0, decrypted.Length);
         }
 
         #endregion

+ 11 - 19
Masuit.Tools/Security/RSACrypt.cs

@@ -36,14 +36,12 @@ namespace Masuit.Tools.Security
         /// </summary>
         public static RsaKey GenerateRsaKeys()
         {
-            using (var rsa = new RSACryptoServiceProvider())
+            using var rsa = new RSACryptoServiceProvider();
+            return RsaKey ??= new RsaKey
             {
-                return RsaKey ?? (RsaKey = new RsaKey
-                {
-                    PrivateKey = rsa.ToXmlString(true),
-                    PublicKey = rsa.ToXmlString(false)
-                });
-            }
+                PrivateKey = rsa.ToXmlString(true),
+                PublicKey = rsa.ToXmlString(false)
+            };
         }
 
         #endregion
@@ -189,7 +187,7 @@ namespace Masuit.Tools.Security
         public static string GetHashString(this string mStrSource)
         {
             //从字符串中取得Hash描述 
-            HashAlgorithm md5 = HashAlgorithm.Create("MD5");
+            var md5 = HashAlgorithm.Create("MD5");
             var buffer = Encoding.UTF8.GetBytes(mStrSource);
             var hashData = md5?.ComputeHash(buffer);
             return Convert.ToBase64String(hashData);
@@ -203,11 +201,8 @@ namespace Masuit.Tools.Security
         public static byte[] GetHashBytes(this FileStream objFile)
         {
             //从文件中取得Hash描述 
-            using (objFile)
-            {
-                HashAlgorithm md5 = HashAlgorithm.Create("MD5");
-                return md5?.ComputeHash(objFile);
-            }
+            var md5 = HashAlgorithm.Create("MD5");
+            return md5?.ComputeHash(objFile);
         }
 
         /// <summary>
@@ -218,12 +213,9 @@ namespace Masuit.Tools.Security
         public static string GetHashString(this FileStream objFile)
         {
             //从文件中取得Hash描述 
-            using (objFile)
-            {
-                HashAlgorithm md5 = HashAlgorithm.Create("MD5");
-                var hashData = md5?.ComputeHash(objFile);
-                return Convert.ToBase64String(hashData);
-            }
+            HashAlgorithm md5 = HashAlgorithm.Create("MD5");
+            var hashData = md5?.ComputeHash(objFile);
+            return Convert.ToBase64String(hashData);
         }
 
         #endregion

+ 42 - 47
Masuit.Tools/Strings/ValidateCode.cs

@@ -42,58 +42,53 @@ namespace Masuit.Tools.Strings
         /// <param name="fontSize">字体大小,默认值22px</param>
         /// <param name="lineHeight">行高,默认36px</param>
         /// <exception cref="Exception">The operation failed.</exception>
-        /// <exception cref="HttpException">The Web application is running under IIS 7 in Integrated mode.</exception>
-        public static void CreateValidateGraphic(this HttpContext context, string validateCode, int fontSize = 22, int lineHeight = 36)
+        public static byte[] CreateValidateGraphic(this HttpContext context, string validateCode, int fontSize = 22, int lineHeight = 36)
         {
-            using (Bitmap image = new Bitmap((int) Math.Ceiling(validateCode.Length * (fontSize + 2.0)), lineHeight))
+            using Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * (fontSize + 2.0)), lineHeight);
+            using Graphics g = Graphics.FromImage(image);
+            //生成随机生成器
+            Random random = new Random();
+            //清空图片背景色
+            g.Clear(Color.White);
+            //画图片的干扰线
+            for (int i = 0; i < 75; i++)
             {
-                using (Graphics g = Graphics.FromImage(image))
-                {
-                    //生成随机生成器
-                    Random random = new Random();
-                    //清空图片背景色
-                    g.Clear(Color.White);
-                    //画图片的干扰线
-                    for (int i = 0; i < 75; i++)
-                    {
-                        int x1 = random.Next(image.Width);
-                        int x2 = random.Next(image.Width);
-                        int y1 = random.Next(image.Height);
-                        int y2 = random.Next(image.Height);
-                        g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
-                    }
-
-                    Font[] fonts =
-                    {
-                        new Font("Arial", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("微软雅黑", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("黑体", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("宋体", fontSize, FontStyle.Bold | FontStyle.Italic),
-                        new Font("楷体", fontSize, FontStyle.Bold | FontStyle.Italic)
-                    };
-                    //渐变.
-                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
-                    g.DrawString(validateCode, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
+                int x1 = random.Next(image.Width);
+                int x2 = random.Next(image.Width);
+                int y1 = random.Next(image.Height);
+                int y2 = random.Next(image.Height);
+                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
+            }
 
-                    //画图片的前景干扰点
-                    for (int i = 0; i < 300; i++)
-                    {
-                        int x = random.Next(image.Width);
-                        int y = random.Next(image.Height);
-                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
-                    }
+            Font[] fonts =
+            {
+                new Font("Arial", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("微软雅黑", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("黑体", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("宋体", fontSize, FontStyle.Bold | FontStyle.Italic),
+                new Font("楷体", fontSize, FontStyle.Bold | FontStyle.Italic)
+            };
+            //渐变.
+            var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
+            g.DrawString(validateCode, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
 
-                    //画图片的边框线
-                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
-                    //保存图片数据
-                    MemoryStream stream = new MemoryStream();
-                    image.Save(stream, ImageFormat.Jpeg);
-                    //输出图片流
-                    context.Response.Clear();
-                    context.Response.ContentType = "image/jpeg";
-                    context.Response.BinaryWrite(stream.ToArray());
-                }
+            //画图片的前景干扰点
+            for (int i = 0; i < 300; i++)
+            {
+                int x = random.Next(image.Width);
+                int y = random.Next(image.Height);
+                image.SetPixel(x, y, Color.FromArgb(random.Next()));
             }
+
+            //画图片的边框线
+            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
+            //保存图片数据
+            using MemoryStream stream = new MemoryStream();
+            image.Save(stream, ImageFormat.Jpeg);
+            //输出图片流
+            context.Response.Clear();
+            context.Response.ContentType = "image/jpeg";
+            return stream.ToArray();
         }
     }
 }

+ 1 - 1
Masuit.Tools/Systems/EnumExt.cs

@@ -101,7 +101,7 @@ namespace Masuit.Tools.Systems
         /// <returns></returns>
         public static Type GetEnumType(Assembly assembly, string typeName)
         {
-            _enumTypeDict = _enumTypeDict ?? LoadEnumTypeDict(assembly);
+            _enumTypeDict ??= LoadEnumTypeDict(assembly);
             if (_enumTypeDict.ContainsKey(typeName))
             {
                 return _enumTypeDict[typeName];

+ 1 - 1
Masuit.Tools/Systems/SnowFlake.cs

@@ -46,7 +46,7 @@ namespace Masuit.Tools.Systems
         /// <returns></returns>
         public static SnowFlake GetInstance()
         {
-            return _snowFlake ?? (_snowFlake = new SnowFlake());
+            return _snowFlake ??= new SnowFlake();
         }
 
         /// <summary>

+ 74 - 104
Masuit.Tools/Win32/Windows.cs

@@ -16,7 +16,7 @@ namespace Masuit.Tools.Win32
     /// </summary>
     public static class Windows
     {
-        /// <summary>
+        /// <summary>  
         /// 跨平台调用C++的方法
         /// </summary>
         /// <param name="hwProc">程序句柄</param>
@@ -71,7 +71,7 @@ namespace Masuit.Tools.Win32
         public static string GetLocalUsedIP()
         {
             string result = RunApp("route", "print", true);
-            Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
+            var m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
             if (m.Success)
             {
                 return m.Groups[2].Value;
@@ -79,12 +79,9 @@ namespace Masuit.Tools.Win32
 
             try
             {
-                string ip;
-                using (System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient())
-                {
-                    c.Connect("www.baidu.com", 80);
-                    ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
-                }
+                using var c = new System.Net.Sockets.TcpClient();
+                c.Connect("www.baidu.com", 80);
+                var ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
 
                 return ip;
             }
@@ -123,22 +120,23 @@ namespace Masuit.Tools.Win32
                 };
                 proc.Start();
 
-                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
+                using var sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default);
+                //上面标记的是原文,下面是我自己调试错误后自行修改的  
+                Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
+                //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
+                if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
                 {
-                    //上面标记的是原文,下面是我自己调试错误后自行修改的  
-                    Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                    //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                    if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                    {
-                        //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
-                        proc.Kill();
-                    }
+                    //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
+                    proc.Kill();
+                }
 
-                    string txt = sr.ReadToEnd();
-                    if (recordLog)
-                        Trace.WriteLine(txt);
-                    return txt;
+                string txt = sr.ReadToEnd();
+                if (recordLog)
+                {
+                    Trace.WriteLine(txt);
                 }
+
+                return txt;
             }
             catch (Exception ex)
             {
@@ -246,14 +244,12 @@ namespace Masuit.Tools.Win32
             {
                 //获取CPU序列号代码 
                 string cpuInfo = " "; //cpu序列号 
-                using (var mc = new ManagementClass("Win32_Processor"))
+                using var mc = new ManagementClass("Win32_Processor");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
-                        {
-                            cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
-                        }
+                        cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                     }
                 }
 
@@ -273,13 +269,9 @@ namespace Masuit.Tools.Win32
         {
             try
             {
-                using (var mCpu = new ManagementClass("Win32_Processor"))
-                {
-                    using (ManagementObjectCollection cpus = mCpu.GetInstances())
-                    {
-                        return cpus.Count;
-                    }
-                }
+                using var mCpu = new ManagementClass("Win32_Processor");
+                using var cpus = mCpu.GetInstances();
+                return cpus.Count;
             }
             catch
             {
@@ -295,27 +287,21 @@ namespace Masuit.Tools.Win32
         /// <returns></returns>
         public static string[] GetCpuMHZ()
         {
-            using (var mc = new ManagementClass("Win32_Processor"))
+            using var mc = new ManagementClass("Win32_Processor");
+            using ManagementObjectCollection cpus = mc.GetInstances();
+            var mhz = new string[cpus.Count];
+            int c = 0;
+            using var mySearch = new ManagementObjectSearcher("select * from Win32_Processor");
+            foreach (ManagementObject mo in mySearch.Get())
             {
-                using (ManagementObjectCollection cpus = mc.GetInstances())
+                using (mo)
                 {
-                    var mhz = new string[cpus.Count];
-                    int c = 0;
-                    using (var mySearch = new ManagementObjectSearcher("select * from Win32_Processor"))
-                    {
-                        foreach (ManagementObject mo in mySearch.Get())
-                        {
-                            using (mo)
-                            {
-                                mhz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
-                                c++;
-                            }
-                        }
-                    }
-
-                    return mhz;
+                    mhz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
+                    c++;
                 }
             }
+
+            return mhz;
         }
 
         /// <summary>
@@ -324,14 +310,12 @@ namespace Masuit.Tools.Win32
         /// <returns></returns>
         public static string GetSizeOfDisk()
         {
-            using (var mc = new ManagementClass("Win32_DiskDrive"))
+            using var mc = new ManagementClass("Win32_DiskDrive");
+            foreach (ManagementObject m in mc.GetInstances())
             {
-                foreach (ManagementObject m in mc.GetInstances())
+                using (m)
                 {
-                    using (m)
-                    {
-                        return m.Properties["Size"].Value.ToString();
-                    }
+                    return m.Properties["Size"].Value.ToString();
                 }
             }
 
@@ -344,17 +328,15 @@ namespace Masuit.Tools.Win32
             {
                 //获取网卡硬件地址 
                 string mac = " ";
-                using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
+                        if ((bool)mo["IPEnabled"])
                         {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                mac = mo["MacAddress"].ToString();
-                                break;
-                            }
+                            mac = mo["MacAddress"].ToString();
+                            break;
                         }
                     }
                 }
@@ -373,20 +355,18 @@ namespace Masuit.Tools.Win32
             {
                 //获取IP地址 
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
+                using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
+                        if ((bool)mo["IPEnabled"])
                         {
-                            if ((bool)mo["IPEnabled"])
-                            {
-                                //st=mo[ "IpAddress "].ToString(); 
-                                Array ar;
-                                ar = (Array)(mo.Properties["IpAddress"].Value);
-                                st = ar.GetValue(0).ToString();
-                                break;
-                            }
+                            //st=mo[ "IpAddress "].ToString(); 
+                            Array ar;
+                            ar = (Array)(mo.Properties["IpAddress"].Value);
+                            st = ar.GetValue(0).ToString();
+                            break;
                         }
                     }
                 }
@@ -405,14 +385,12 @@ namespace Masuit.Tools.Win32
             {
                 //获取硬盘ID 
                 string hdid = Empty;
-                using (var mc = new ManagementClass("Win32_DiskDrive"))
+                using var mc = new ManagementClass("Win32_DiskDrive");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
-                        {
-                            hdid = (string)mo.Properties["Model"].Value;
-                        }
+                        hdid = (string)mo.Properties["Model"].Value;
                     }
                 }
 
@@ -433,14 +411,12 @@ namespace Masuit.Tools.Win32
             try
             {
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_ComputerSystem"))
+                using var mc = new ManagementClass("Win32_ComputerSystem");
+                foreach (ManagementObject mo in mc.GetInstances())
                 {
-                    foreach (ManagementObject mo in mc.GetInstances())
+                    using (mo)
                     {
-                        using (mo)
-                        {
-                            st = mo["UserName"].ToString();
-                        }
+                        st = mo["UserName"].ToString();
                     }
                 }
 
@@ -457,15 +433,13 @@ namespace Masuit.Tools.Win32
             try
             {
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_ComputerSystem"))
+                using var mc = new ManagementClass("Win32_ComputerSystem");
+                foreach (var o in mc.GetInstances())
                 {
-                    foreach (var o in mc.GetInstances())
+                    using (o)
                     {
-                        using (o)
-                        {
-                            var mo = (ManagementObject)o;
-                            st = mo["SystemType"].ToString();
-                        }
+                        var mo = (ManagementObject)o;
+                        st = mo["SystemType"].ToString();
                     }
                 }
 
@@ -482,17 +456,13 @@ namespace Masuit.Tools.Win32
             try
             {
                 string st = Empty;
-                using (var mc = new ManagementClass("Win32_ComputerSystem"))
+                using var mc = new ManagementClass("Win32_ComputerSystem");
+                using var moc = mc.GetInstances();
+                foreach (var o in moc)
                 {
-                    using (ManagementObjectCollection moc = mc.GetInstances())
-                    {
-                        foreach (var o in moc)
-                        {
-                            var mo = (ManagementObject)o;
+                    var mo = (ManagementObject)o;
 
-                            st = mo["TotalPhysicalMemory"].ToString();
-                        }
-                    }
+                    st = mo["TotalPhysicalMemory"].ToString();
                 }
 
                 return st;

+ 20 - 22
Masuit.Tools/Win32/WindowsCommand.cs

@@ -23,31 +23,29 @@ namespace Masuit.Tools.Win32
             string output = "";
             if (!string.IsNullOrEmpty(dosCommand))
             {
-                using (Process process = new Process()) //创建进程对象  
-                {
-                    ProcessStartInfo startinfo = new ProcessStartInfo(); //创建进程时使用的一组值,如下面的属性  
-                    startinfo.FileName = "cmd.exe"; //设定需要执行的命令程序  
-                    //以下是隐藏cmd窗口的方法  
-                    startinfo.Arguments = "/c" + dosCommand; //设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出  
-                    startinfo.UseShellExecute = false; //不使用系统外壳程序启动  
-                    startinfo.RedirectStandardInput = false; //不重定向输入  
-                    startinfo.RedirectStandardOutput = true; //重定向输出,而不是默认的显示在dos控制台上  
-                    startinfo.CreateNoWindow = true; //不创建窗口  
-                    process.StartInfo = startinfo;
+                using var process = new Process();
+                ProcessStartInfo startinfo = new ProcessStartInfo(); //创建进程时使用的一组值,如下面的属性  
+                startinfo.FileName = "cmd.exe"; //设定需要执行的命令程序  
+                //以下是隐藏cmd窗口的方法  
+                startinfo.Arguments = "/c" + dosCommand; //设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出  
+                startinfo.UseShellExecute = false; //不使用系统外壳程序启动  
+                startinfo.RedirectStandardInput = false; //不重定向输入  
+                startinfo.RedirectStandardOutput = true; //重定向输出,而不是默认的显示在dos控制台上  
+                startinfo.CreateNoWindow = true; //不创建窗口  
+                process.StartInfo = startinfo;
 
-                    if (process.Start()) //开始进程  
+                if (process.Start()) //开始进程  
+                {
+                    if (outtime == 0)
                     {
-                        if (outtime == 0)
-                        {
-                            process.WaitForExit();
-                        }
-                        else
-                        {
-                            process.WaitForExit(outtime);
-                        }
-
-                        output = process.StandardOutput.ReadToEnd(); //读取进程的输出  
+                        process.WaitForExit();
                     }
+                    else
+                    {
+                        process.WaitForExit(outtime);
+                    }
+
+                    output = process.StandardOutput.ReadToEnd(); //读取进程的输出  
                 }
 
                 return output;

+ 16 - 13
Masuit.Tools/app.config

@@ -1,15 +1,18 @@
 <?xml version="1.0" encoding="utf-8"?>
 <configuration>
-  <runtime>
-    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
-      <dependentAssembly>
-        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
-        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
-      </dependentAssembly>
-      <dependentAssembly>
-        <assemblyIdentity name="AngleSharp" publicKeyToken="e83494dcdc6d31ea" culture="neutral"/>
-        <bindingRedirect oldVersion="0.0.0.0-0.13.0.0" newVersion="0.13.0.0"/>
-      </dependentAssembly>
-    </assemblyBinding>
-  </runtime>
-<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>
+    <startup>
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
+    </startup>
+    <runtime>
+        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+            <dependentAssembly>
+                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
+            </dependentAssembly>
+            <dependentAssembly>
+                <assemblyIdentity name="AngleSharp" publicKeyToken="e83494dcdc6d31ea" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-0.13.0.0" newVersion="0.13.0.0"/>
+            </dependentAssembly>
+        </assemblyBinding>
+    </runtime>
+</configuration>

+ 1 - 0
NetCoreTest/NetCoreTest.csproj

@@ -4,6 +4,7 @@
     <TargetFramework>netcoreapp3.0</TargetFramework>
     <RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
     <RunAnalyzersDuringLiveAnalysis>false</RunAnalyzersDuringLiveAnalysis>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

+ 3 - 2
NetCoreTest/Startup.cs

@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
 
 namespace NetCoreTest
 {
@@ -20,11 +21,11 @@ namespace NetCoreTest
         public void ConfigureServices(IServiceCollection services)
         {
             services.AddStaticHttpContext();
-            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
+            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
         }
 
         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
-        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
         {
             if (env.IsDevelopment())
             {

+ 10 - 6
Test/App.config

@@ -1,17 +1,21 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
 <configuration>
     <startup> 
-        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
     </startup>
   <runtime>
     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
       <dependentAssembly>
-        <assemblyIdentity name="DnsClient" publicKeyToken="4574bb5573c51424" culture="neutral"/>
-        <bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0"/>
+        <assemblyIdentity name="DnsClient" publicKeyToken="4574bb5573c51424" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0" />
       </dependentAssembly>
       <dependentAssembly>
-        <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
-        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
+        <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="AngleSharp" publicKeyToken="e83494dcdc6d31ea" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-0.13.0.0" newVersion="0.13.0.0" />
       </dependentAssembly>
     </assemblyBinding>
   </runtime>

+ 2 - 0
Test/Test.csproj

@@ -25,6 +25,7 @@
     <CodeAnalysisRuleSet>
     </CodeAnalysisRuleSet>
     <RunCodeAnalysis>true</RunCodeAnalysis>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <PlatformTarget>AnyCPU</PlatformTarget>
@@ -37,6 +38,7 @@
     <RunCodeAnalysis>true</RunCodeAnalysis>
     <CodeAnalysisRuleSet>
     </CodeAnalysisRuleSet>
+    <LangVersion>8.0</LangVersion>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="System" />