懒得勤快 7 tahun lalu
induk
melakukan
677c617d54

+ 8 - 51
Masuit.Tools.Core/DateTimeExt/DateUtil.cs

@@ -89,18 +89,7 @@ namespace Masuit.Tools.Core.DateTimeExt
         /// <returns>本年的天数</returns>
         public static int GetDaysOfYear(this DateTime _, int iYear)
         {
-            int cnt;
-            if (IsRuYear(iYear))
-            {
-                //闰年多 1 天 即:2 月为 29 天
-                cnt = 366;
-            }
-            else
-            {
-                //非闰年少1天 即:2 月为 28 天
-                cnt = 365;
-            }
-            return cnt;
+            return IsRuYear(iYear) ? 366 : 365;
         }
 
         /// <summary>本年有多少天</summary>
@@ -136,17 +125,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                     days = 31;
                     break;
                 case 2:
-                    if (IsRuYear(iYear))
-                    {
-                        //闰年多 1 天 即:2 月为 29 天
-                        days = 29;
-                    }
-                    else
-                    {
-                        //--非闰年少1天 即:2 月为 28 天
-                        days = 28;
-                    }
-
+                    days = IsRuYear(iYear) ? 29 : 28;
                     break;
                 case 3:
                     days = 31;
@@ -188,9 +167,9 @@ namespace Masuit.Tools.Core.DateTimeExt
             //--------------------------------//
             //从dt中取得当前的年,月信息  --//
             //--------------------------------//
-            int month, days = 0;
+            int days = 0;
             var year = dt.Year;
-            month = dt.Month;
+            var month = dt.Month;
 
             //--利用年月信息,得到当前月的天数信息。
             switch (month)
@@ -199,17 +178,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                     days = 31;
                     break;
                 case 2:
-                    if (IsRuYear(year))
-                    {
-                        //闰年多 1 天 即:2 月为 29 天
-                        days = 29;
-                    }
-                    else
-                    {
-                        //--非闰年少1天 即:2 月为 28 天
-                        days = 28;
-                    }
-
+                    days = IsRuYear(year) ? 29 : 28;
                     break;
                 case 3:
                     days = 31;
@@ -325,11 +294,7 @@ namespace Masuit.Tools.Core.DateTimeExt
             //例如:2003
             var n = iYear;
 
-            if ((n % 400 == 0) || (n % 4 == 0 && n % 100 != 0))
-            {
-                return true;
-            }
-            return false;
+            return n % 400 == 0 || n % 4 == 0 && n % 100 != 0;
         }
 
         /// <summary>
@@ -339,16 +304,8 @@ namespace Masuit.Tools.Core.DateTimeExt
         /// <returns>True/False</returns>
         public static bool IsDateTime(this string strDate)
         {
-            try
-            {
-                DateTime oDate = DateTime.Parse(strDate);
-                if (oDate.CompareTo(DateTime.Parse("1800-1-1")) > 0) return true;
-                return false;
-            }
-            catch
-            {
-                return false;
-            }
+            DateTime.TryParse(strDate, out var result);
+            return result.CompareTo(DateTime.Parse("1800-1-1")) > 0;
         }
     }
 }

+ 8 - 16
Masuit.Tools.Core/DateTimeExt/TimeHelper.cs

@@ -1,8 +1,7 @@
 using System;
 using System.Globalization;
-using Masuit.Tools.Logging;
 
-namespace Masuit.Tools.DateTimeExt
+namespace Masuit.Tools.Core.DateTimeExt
 {
     /// <summary>
     /// 时间相关操作帮助类
@@ -310,23 +309,16 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>时间差</returns>
         public static string DateDiff(this DateTime dateTime1, DateTime dateTime2)
         {
-            string dateDiff = null;
-            try
+            string dateDiff;
+            TimeSpan ts = dateTime2 - dateTime1;
+            if (ts.Days >= 1)
             {
-                TimeSpan ts = dateTime2 - dateTime1;
-                if (ts.Days >= 1)
-                {
-                    dateDiff = dateTime1.Month + "月" + dateTime1.Day + "日";
-                }
-                else
-                {
-                    if (ts.Hours > 1) dateDiff = ts.Hours + "小时前";
-                    else dateDiff = ts.Minutes + "分钟前";
-                }
+                dateDiff = dateTime1.Month + "月" + dateTime1.Day + "日";
             }
-            catch (Exception e)
+            else
             {
-                LogManager.Error(e);
+                if (ts.Hours > 1) dateDiff = ts.Hours + "小时前";
+                else dateDiff = ts.Minutes + "分钟前";
             }
             return dateDiff;
         }

+ 9 - 8
Masuit.Tools.Core/Html/HtmlTools.cs

@@ -10,9 +10,9 @@ using System.Text.RegularExpressions;
 using System.Web;
 using System.Xml;
 using Ganss.XSS;
-using Masuit.Tools.Logging;
+using Masuit.Tools.Core.Logging;
 
-namespace Masuit.Tools.Html
+namespace Masuit.Tools.Core.Html
 {
     /// <summary>
     /// html工具类
@@ -1135,7 +1135,6 @@ namespace Masuit.Tools.Html
             try
             {
                 Uri baseUri = new Uri(sUrl);
-
                 return baseUri.Scheme + "://" + baseUri.Authority;
             }
             catch
@@ -1304,7 +1303,7 @@ namespace Masuit.Tools.Html
                 }
                 catch (ArgumentException)
                 {//指定的编码不可识别
-                    content = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
+                    content = Encoding.GetEncoding("gb2312").GetString(buffer);
                 }
 
                 //content = CText.RemoveByReg(content, @"<!--[\s\S]*?-->");
@@ -1479,7 +1478,9 @@ ReCatch:
                 var ipHostInfo = Dns.GetHostEntry(site.Host);
                 IPAddress ipAddress = ipHostInfo.AddressList[0];
                 IPEndPoint remoteEP = new IPEndPoint(ipAddress, site.Port);
-                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = iTimeOut, ReceiveTimeout = iTimeOut };
+                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                sock.SendTimeout = iTimeOut;
+                sock.ReceiveTimeout = iTimeOut;
                 sock.Connect(remoteEP);
                 foreach (KeyValuePair<int, string> kvUrl in listUrl)
                 {
@@ -1511,7 +1512,7 @@ ReCatch:
                         }
                         catch (Exception Ex)
                         {
-                            string str = Ex.Message;
+                            //string str = Ex.Message;
                             nBytes = -1;
                         }
                         if (nBytes <= 0) break;
@@ -1542,13 +1543,13 @@ ReCatch:
                     } while (nBytes > 0);
 
                     listResult.Add(new KeyValuePair<int, string>(kvUrl.Key, sbHtml.ToString()));
-                    sbHtml = null;
+                    //sbHtml = null;
                     sbHtml = new StringBuilder();
                 }
             }
             catch (Exception Ex)
             {
-                string s = Ex.Message;
+                //string s = Ex.Message;
                 try
                 {
                     sock.Shutdown(SocketShutdown.Both);

+ 24 - 23
Masuit.Tools.Core/Logging/LogManager.cs

@@ -6,9 +6,8 @@ using System.Linq;
 using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading.Tasks;
-using static System.DateTime;
 
-namespace Masuit.Tools.Logging
+namespace Masuit.Tools.Core.Logging
 {
     /// <summary>
     /// 日志组件
@@ -18,7 +17,6 @@ namespace Masuit.Tools.Logging
         static readonly ConcurrentQueue<Tuple<string, string>> LogQueue = new ConcurrentQueue<Tuple<string, string>>();
 
         public static event Action<string> Event;
-
         static LogManager()
         {
             var writeTask = new Task(obj =>
@@ -58,115 +56,118 @@ namespace Masuit.Tools.Logging
         /// <summary>
         /// 日志存放目录,默认日志放在当前应用程序运行目录下的logs文件夹中
         /// </summary>
-        public static string LogDirectory { get; set; } = Path.Combine(AppContext.BaseDirectory, "Logs");
-
+        public static string LogDirectory
+        {
+            get => Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).Any(s => s.Contains("Web.config")) ? AppDomain.CurrentDomain.BaseDirectory + @"App_Data\Logs\" : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
+            set { }
+        }
         /// <summary>
         /// 写入Info级别的日志
         /// </summary>
         /// <param name="info"></param>
-        public static void Info(string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}  {info}"));
+        public static void Info(string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}  {info}"));
 
         /// <summary>
         /// 写入Info级别的日志
         /// </summary>
         /// <param name="source"></param>
         /// <param name="info"></param>
-        public static void Info(string source, string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source}  {info}"));
+        public static void Info(string source, string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source}  {info}"));
 
         /// <summary>
         /// 写入Info级别的日志
         /// </summary>
         /// <param name="source"></param>
         /// <param name="info"></param>
-        public static void Info(Type source, string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source.FullName}  {info}"));
+        public static void Info(Type source, string info) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source.FullName}  {info}"));
 
         /// <summary>
         /// 写入debug级别日志
         /// </summary>
         /// <param name="debug">异常对象</param>
-        public static void Debug(string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {debug}"));
+        public static void Debug(string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {debug}"));
 
         /// <summary>
         /// 写入debug级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="debug">异常对象</param>
-        public static void Debug(string source, string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source}  {debug}"));
+        public static void Debug(string source, string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source}  {debug}"));
 
         /// <summary>
         /// 写入debug级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="debug">异常对象</param>
-        public static void Debug(Type source, string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source.FullName}  {debug}"));
+        public static void Debug(Type source, string debug) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source.FullName}  {debug}"));
 
         /// <summary>
         /// 写入error级别日志
         /// </summary>
         /// <param name="error">异常对象</param>
-        public static void Error(Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {error.Source}  {error.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {error.Source}  {error.StackTrace}"));
+        public static void Error(Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {error.Source}  {error.Message}{Environment.NewLine}{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {error.Source}  {error.StackTrace}"));
 
         /// <summary>
         /// 写入error级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="error">异常对象</param>
-        public static void Error(Type source, Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error.StackTrace}"));
+        public static void Error(Type source, Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error.Message}{Environment.NewLine}{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error.StackTrace}"));
 
         /// <summary>
         /// 写入error级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="error">异常信息</param>
-        public static void Error(Type source, string error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error}"));
+        public static void Error(Type source, string error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error}"));
 
         /// <summary>
         /// 写入error级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="error">异常对象</param>
-        public static void Error(string source, Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error.StackTrace}"));
+        public static void Error(string source, Exception error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error.Message}{Environment.NewLine}{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error.StackTrace}"));
 
         /// <summary>
         /// 写入error级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="error">异常信息</param>
-        public static void Error(string source, string error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error}"));
+        public static void Error(string source, string error) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error}"));
 
         /// <summary>
         /// 写入fatal级别日志
         /// </summary>
         /// <param name="fatal">异常对象</param>
-        public static void Fatal(Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {fatal.Source}  {fatal.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {fatal.Source}  {fatal.StackTrace}"));
+        public static void Fatal(Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {fatal.Source}  {fatal.Message}{Environment.NewLine}{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {fatal.Source}  {fatal.StackTrace}"));
 
         /// <summary>
         /// 写入fatal级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="fatal">异常对象</param>
-        public static void Fatal(Type source, Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal.StackTrace}"));
+        public static void Fatal(Type source, Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal.Message}{Environment.NewLine}{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal.StackTrace}"));
 
         /// <summary>
         /// 写入fatal级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="fatal">异常对象</param>
-        public static void Fatal(Type source, string fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal}"));
+        public static void Fatal(Type source, string fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal}"));
 
         /// <summary>
         /// 写入fatal级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="fatal">异常对象</param>
-        public static void Fatal(string source, Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal.Message}{Environment.NewLine}{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal.StackTrace}"));
+        public static void Fatal(string source, Exception fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal.Message}{Environment.NewLine}{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal.StackTrace}"));
 
         /// <summary>
         /// 写入fatal级别日志
         /// </summary>
         /// <param name="source">异常源的类型</param>
         /// <param name="fatal">异常对象</param>
-        public static void Fatal(string source, string fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal}"));
+        public static void Fatal(string source, string fatal) => LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal}"));
 
         private static string GetLogPath()
         {
@@ -177,7 +178,7 @@ namespace Masuit.Tools.Logging
                 Directory.CreateDirectory(logDir);
             }
             string extension = ".log";
-            string fileNameNotExt = String.Concat(Now.ToString("yyyyMMdd"));
+            string fileNameNotExt = String.Concat(DateTime.Now.ToString("yyyyMMdd"));
             string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension);
             List<string> filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList();
 
@@ -216,12 +217,12 @@ namespace Masuit.Tools.Logging
                 }
                 using (StreamWriter sw = File.AppendText(logPath))
                 {
-                    Event(logContent);
                     sw.Write(logContent);
                 }
             }
             catch (Exception)
             {
+                // ignored
             }
         }
     }

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

@@ -2,7 +2,7 @@
 
   <PropertyGroup>
     <TargetFramework>netcoreapp2.0</TargetFramework>
-    <Version>1.9.6</Version>
+    <Version>1.9.7</Version>
     <Authors>懒得勤快</Authors>
     <Company>masuit.com</Company>
     <Description>包含一些常用的操作类,大都是静态类,加密解密,反射操作,硬件信息,字符串扩展方法,日期时间扩展操作,大文件拷贝,图像裁剪,html处理,验证码、NoSql等常用封装。

+ 6 - 6
Masuit.Tools.Core/NoSQL/RedisHelper.cs

@@ -67,9 +67,9 @@ namespace Masuit.Tools.NoSQL
         #region 构造函数
 
         /// <summary>
-        /// 构造函数,使用该构造函数需要先在config中配置链接字符串,连接字符串在config配置文件中的ConnectionStrings节下配置,name固定为RedisHosts,值的格式:127.0.0.1:6379,allowadmin=true,若未正确配置,将按默认值“127.0.0.1:6379,allowadmin=true”进行操作,如:<br/>
+        /// 构造函数,使用该构造函数需要先在config中配置链接字符串,连接字符串在config配置文件中的ConnectionStrings节下配置,name固定为RedisHosts,值的格式:127.0.0.1:6379,allowadmin=true,若未正确配置,将按默认值“127.0.0.1:6379,allowadmin=true,abortConnect=false”进行操作,如:<br/>
         /// &lt;connectionStrings&gt;<br/>
-        ///      &lt;add name = "RedisHosts" connectionString="127.0.0.1:6379,allowadmin=true"/&gt;<br/>
+        ///      &lt;add name = "RedisHosts" connectionString="127.0.0.1:6379,allowadmin=true,abortConnect=false"/&gt;<br/>
         /// &lt;/connectionStrings&gt;
         /// </summary>
         /// <param name="dbNum">数据库编号</param>
@@ -80,7 +80,7 @@ namespace Masuit.Tools.NoSQL
         /// <summary>
         /// 构造函数
         /// </summary>
-        /// <param name="readWriteHosts">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true</param>
+        /// <param name="readWriteHosts">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true,abortConnect=false</param>
         /// <param name="dbNum">数据库的编号</param>
         public RedisHelper(string readWriteHosts, int dbNum = 0)
         {
@@ -103,7 +103,7 @@ namespace Masuit.Tools.NoSQL
         /// <summary>
         /// 构造函数
         /// </summary>
-        /// <param name="readWriteHosts">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true</param>
+        /// <param name="readWriteHosts">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true,abortConnect=false</param>
         /// <param name="dbNum">数据库的编号</param>
         private RedisHelper(string readWriteHosts, int dbNum, int _)
         {
@@ -147,7 +147,7 @@ namespace Masuit.Tools.NoSQL
         /// <summary>
         /// 从对象池获取默认实例
         /// </summary>
-        /// <param name="conn">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true</param>
+        /// <param name="conn">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true,abortConnect=false</param>
         /// <param name="db">数据库的编号</param>
         /// <returns></returns>
         public static RedisHelper GetInstance(string conn, int db = 0)
@@ -158,7 +158,7 @@ namespace Masuit.Tools.NoSQL
         /// <summary>
         /// 获取单例
         /// </summary>
-        /// <param name="conn">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true</param>
+        /// <param name="conn">Redis服务器连接字符串,格式:127.0.0.1:6379,allowadmin=true,abortConnect=false</param>
         /// <param name="db">数据库的编号</param>
         /// <returns></returns>
         public static RedisHelper GetSingleInstance(string conn, int db = 0)

+ 23 - 0
Masuit.Tools.Core/Systems/Disposable.cs

@@ -0,0 +1,23 @@
+using System;
+
+namespace Masuit.Tools.Core.Systems
+{
+    public abstract class Disposable : IDisposable
+    {
+        private bool isDisposed;
+
+        ~Disposable()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            isDisposed = true;
+            GC.SuppressFinalize(this);
+        }
+
+        public abstract void Dispose(bool disposing);
+    }
+}

+ 8 - 54
Masuit.Tools/DateTimeExt/DateUtil.cs

@@ -89,18 +89,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>本年的天数</returns>
         public static int GetDaysOfYear(this DateTime _, int iYear)
         {
-            int cnt;
-            if (IsRuYear(iYear))
-            {
-                //闰年多 1 天 即:2 月为 29 天
-                cnt = 366;
-            }
-            else
-            {
-                //非闰年少1天 即:2 月为 28 天
-                cnt = 365;
-            }
-            return cnt;
+            return IsRuYear(iYear) ? 366 : 365;
         }
 
         /// <summary>本年有多少天</summary>
@@ -136,17 +125,7 @@ namespace Masuit.Tools.DateTimeExt
                     days = 31;
                     break;
                 case 2:
-                    if (IsRuYear(iYear))
-                    {
-                        //闰年多 1 天 即:2 月为 29 天
-                        days = 29;
-                    }
-                    else
-                    {
-                        //--非闰年少1天 即:2 月为 28 天
-                        days = 28;
-                    }
-
+                    days = IsRuYear(iYear) ? 29 : 28;
                     break;
                 case 3:
                     days = 31;
@@ -188,9 +167,9 @@ namespace Masuit.Tools.DateTimeExt
             //--------------------------------//
             //从dt中取得当前的年,月信息  --//
             //--------------------------------//
-            int month, days = 0;
+            int days = 0;
             var year = dt.Year;
-            month = dt.Month;
+            var month = dt.Month;
 
             //--利用年月信息,得到当前月的天数信息。
             switch (month)
@@ -199,17 +178,7 @@ namespace Masuit.Tools.DateTimeExt
                     days = 31;
                     break;
                 case 2:
-                    if (IsRuYear(year))
-                    {
-                        //闰年多 1 天 即:2 月为 29 天
-                        days = 29;
-                    }
-                    else
-                    {
-                        //--非闰年少1天 即:2 月为 28 天
-                        days = 28;
-                    }
-
+                    days = IsRuYear(year) ? 29 : 28;
                     break;
                 case 3:
                     days = 31;
@@ -325,14 +294,7 @@ namespace Masuit.Tools.DateTimeExt
             //例如:2003
             var n = iYear;
 
-            if ((n % 400 == 0) || (n % 4 == 0 && n % 100 != 0))
-            {
-                return true;
-            }
-            else
-            {
-                return false;
-            }
+            return n % 400 == 0 || n % 4 == 0 && n % 100 != 0;
         }
 
         /// <summary>
@@ -342,16 +304,8 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>True/False</returns>
         public static bool IsDateTime(this string strDate)
         {
-            try
-            {
-                DateTime oDate = DateTime.Parse(strDate);
-                if (oDate.CompareTo(DateTime.Parse("1800-1-1")) > 0) return true;
-                return false;
-            }
-            catch (Exception)
-            {
-                return false;
-            }
+            DateTime.TryParse(strDate, out var result);
+            return result.CompareTo(DateTime.Parse("1800-1-1")) > 0;
         }
     }
 }

+ 7 - 15
Masuit.Tools/DateTimeExt/TimeHelper.cs

@@ -1,6 +1,5 @@
 using System;
 using System.Globalization;
-using Masuit.Tools.Logging;
 
 namespace Masuit.Tools.DateTimeExt
 {
@@ -310,23 +309,16 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>时间差</returns>
         public static string DateDiff(this DateTime dateTime1, DateTime dateTime2)
         {
-            string dateDiff = null;
-            try
+            string dateDiff;
+            TimeSpan ts = dateTime2 - dateTime1;
+            if (ts.Days >= 1)
             {
-                TimeSpan ts = dateTime2 - dateTime1;
-                if (ts.Days >= 1)
-                {
-                    dateDiff = dateTime1.Month + "月" + dateTime1.Day + "日";
-                }
-                else
-                {
-                    if (ts.Hours > 1) dateDiff = ts.Hours + "小时前";
-                    else dateDiff = ts.Minutes + "分钟前";
-                }
+                dateDiff = dateTime1.Month + "月" + dateTime1.Day + "日";
             }
-            catch (Exception e)
+            else
             {
-                LogManager.Error(e);
+                if (ts.Hours > 1) dateDiff = ts.Hours + "小时前";
+                else dateDiff = ts.Minutes + "分钟前";
             }
             return dateDiff;
         }

+ 15 - 62
Masuit.Tools/Extensions.cs

@@ -1042,14 +1042,8 @@ namespace Masuit.Tools
         /// <returns>int类型的数字</returns>
         public static int ToInt32(this string s)
         {
-            try
-            {
-                return Convert.ToInt32(s);
-            }
-            catch
-            {
-                return 0;
-            }
+            int.TryParse(s, out int result);
+            return result;
         }
 
         /// <summary>
@@ -1059,14 +1053,8 @@ namespace Masuit.Tools
         /// <returns>int类型的数字</returns>
         public static long ToInt64(this string s)
         {
-            try
-            {
-                return Convert.ToInt64(s);
-            }
-            catch
-            {
-                return 0;
-            }
+            long.TryParse(s, out var result);
+            return result;
         }
 
         /// <summary>
@@ -1076,14 +1064,8 @@ namespace Masuit.Tools
         /// <returns>double类型的数据</returns>
         public static double ToDouble(this string s)
         {
-            try
-            {
-                return Convert.ToDouble(s);
-            }
-            catch
-            {
-                return 0;
-            }
+            double.TryParse(s, out var result);
+            return result;
         }
 
         /// <summary>
@@ -1093,14 +1075,8 @@ namespace Masuit.Tools
         /// <returns>int类型的数字</returns>
         public static decimal ToDecimal(this string s)
         {
-            try
-            {
-                return Convert.ToDecimal(s);
-            }
-            catch
-            {
-                return 0;
-            }
+            decimal.TryParse(s, out var result);
+            return result;
         }
 
         /// <summary>
@@ -1110,14 +1086,7 @@ namespace Masuit.Tools
         /// <returns>int类型的数字</returns>
         public static decimal ToDecimal(this double s)
         {
-            try
-            {
-                return Convert.ToDecimal(s);
-            }
-            catch
-            {
-                return 0;
-            }
+            return new decimal(s);
         }
 
         /// <summary>
@@ -1127,14 +1096,7 @@ namespace Masuit.Tools
         /// <returns>double类型的数据</returns>
         public static double ToDouble(this decimal s)
         {
-            try
-            {
-                return Convert.ToDouble(s);
-            }
-            catch
-            {
-                return 0;
-            }
+            return (double)s;
         }
 
         /// <summary>
@@ -1316,8 +1278,7 @@ namespace Masuit.Tools
         {
             if (s.Length == 18)
             {
-                long n;
-                if (long.TryParse(s.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(s.Replace('x', '0').Replace('X', '0'), out n) == false)
+                if (long.TryParse(s.Remove(17), out var n) == false || n < Math.Pow(10, 16) || long.TryParse(s.Replace('x', '0').Replace('X', '0'), out n) == false)
                 {
                     return false; //数字验证  
                 }
@@ -1356,8 +1317,7 @@ namespace Masuit.Tools
 
             if (s.Length == 15)
             {
-                long n;
-                if (long.TryParse(s, out n) == false || n < Math.Pow(10, 14))
+                if (long.TryParse(s, out var n) == false || n < Math.Pow(10, 14))
                 {
                     return false; //数字验证  
                 }
@@ -1369,8 +1329,7 @@ namespace Masuit.Tools
                 }
 
                 string birth = s.Substring(6, 6).Insert(4, "-").Insert(2, "-");
-                DateTime time;
-                if (DateTime.TryParse(birth, out time) == false)
+                if (DateTime.TryParse(birth, out _) == false)
                 {
                     return false; //生日验证  
                 }
@@ -1499,14 +1458,8 @@ namespace Masuit.Tools
         /// <returns></returns>
         public static DateTime ToDateTime(this string value)
         {
-            try
-            {
-                return DateTime.Parse(value);
-            }
-            catch
-            {
-                return default(DateTime);
-            }
+            DateTime.TryParse(value, out var result);
+            return result;
         }
 
         /// <summary>

+ 91 - 85
Masuit.Tools/Files/Compress.cs

@@ -23,10 +23,8 @@ namespace Masuit.Tools.Files
         /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
         public static void PackFiles(string filename, string directory)
         {
-            FastZip fz = new FastZip();
-            fz.CreateEmptyDirectories = true;
+            FastZip fz = new FastZip { CreateEmptyDirectories = true };
             fz.CreateZip(filename, directory, true, "");
-            fz = null;
         }
 
         /// <summary>
@@ -36,8 +34,7 @@ namespace Masuit.Tools.Files
         /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
         public static async void PackFilesAsync(string filename, string directory)
         {
-            FastZip fz = new FastZip();
-            fz.CreateEmptyDirectories = true;
+            FastZip fz = new FastZip { CreateEmptyDirectories = true };
             await Task.Run(() =>
             {
                 fz.CreateZip(filename, directory, true, "");
@@ -71,11 +68,10 @@ namespace Masuit.Tools.Files
                     {
                         using (FileStream streamWriter = File.Create(dir + theEntry.Name))
                         {
-                            int size = 2048;
                             byte[] data = new byte[2048];
                             while (true)
                             {
-                                size = s.Read(data, 0, data.Length);
+                                var size = s.Read(data, 0, data.Length);
                                 if (size > 0)
                                     streamWriter.Write(data, 0, size);
                                 else
@@ -112,11 +108,10 @@ namespace Masuit.Tools.Files
                         {
                             using (FileStream streamWriter = File.Create(dir + theEntry.Name))
                             {
-                                int size = 2048;
                                 byte[] data = new byte[2048];
                                 while (true)
                                 {
-                                    size = s.Read(data, 0, data.Length);
+                                    var size = s.Read(data, 0, data.Length);
                                     if (size > 0)
                                         streamWriter.Write(data, 0, size);
                                     else
@@ -143,16 +138,14 @@ namespace Masuit.Tools.Files
         /// <summary>
         /// 压缩
         /// </summary>
-        /// <param name="FileToZip">待压缩的文件目录或文件</param>
-        /// <param name="ZipedFile">生成的目标文件</param>
+        /// <param name="fileToZip">待压缩的文件目录或文件</param>
+        /// <param name="zipedFile">生成的目标文件</param>
         /// <param name="level">压缩级别,默认值6</param>
-        public static bool Zip(string FileToZip, string ZipedFile, int level = 6)
+        public static bool Zip(string fileToZip, string zipedFile, int level = 6)
         {
-            if (Directory.Exists(FileToZip))
-                return ZipFileDictory(FileToZip, ZipedFile, level);
-            if (File.Exists(FileToZip))
-                return ZipFile(FileToZip, ZipedFile, level);
-            return false;
+            if (Directory.Exists(fileToZip))
+                return ZipFileDictory(fileToZip, zipedFile, level);
+            return File.Exists(fileToZip) && ZipFile(fileToZip, zipedFile, level);
         }
 
         /// <summary>
@@ -216,23 +209,22 @@ namespace Masuit.Tools.Files
         /// <summary>
         /// 解压
         /// </summary>
-        /// <param name="FileToUpZip">待解压的文件</param>
-        /// <param name="ZipedFolder">解压目标存放目录</param>
-        public static void UnZip(string FileToUpZip, string ZipedFolder)
+        /// <param name="fileToUpZip">待解压的文件</param>
+        /// <param name="zipedFolder">解压目标存放目录</param>
+        public static void UnZip(string fileToUpZip, string zipedFolder)
         {
-            if (!File.Exists(FileToUpZip))
+            if (!File.Exists(fileToUpZip))
                 return;
-            if (!Directory.Exists(ZipedFolder))
-                Directory.CreateDirectory(ZipedFolder);
-            ZipEntry theEntry = null;
-            string fileName;
-            using (ZipInputStream s = new ZipInputStream(File.OpenRead(FileToUpZip)))
+            if (!Directory.Exists(zipedFolder))
+                Directory.CreateDirectory(zipedFolder);
+            using (ZipInputStream s = new ZipInputStream(File.OpenRead(fileToUpZip)))
             {
+                ZipEntry theEntry;
                 while ((theEntry = s.GetNextEntry()) != null)
                 {
                     if (theEntry.Name != string.Empty)
                     {
-                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
+                        var fileName = Path.Combine(zipedFolder, theEntry.Name);
                         if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                         {
                             Directory.CreateDirectory(fileName);
@@ -240,11 +232,10 @@ namespace Masuit.Tools.Files
                         }
                         using (FileStream streamWriter = File.Create(fileName))
                         {
-                            int size = 2048;
                             byte[] data = new byte[2048];
                             while (true)
                             {
-                                size = s.Read(data, 0, data.Length);
+                                var size = s.Read(data, 0, data.Length);
                                 if (size > 0)
                                     streamWriter.Write(data, 0, size);
                                 else
@@ -270,7 +261,6 @@ namespace Masuit.Tools.Files
         /// <param name="parentFolderName">父级文件夹</param>
         private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
         {
-            bool res = true;
             Crc32 crc = new Crc32();
             var entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
             s.PutNextEntry(entry);
@@ -282,10 +272,11 @@ namespace Masuit.Tools.Files
                 {
                     byte[] buffer = new byte[fs.Length];
                     fs.Read(buffer, 0, buffer.Length);
-                    entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
-                    entry.DateTime = DateTime.Now;
-                    entry.Size = fs.Length;
-                    fs.Close();
+                    entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)))
+                    {
+                        DateTime = DateTime.Now,
+                        Size = fs.Length
+                    };
                     crc.Reset();
                     crc.Update(buffer);
                     entry.Crc = crc.Value;
@@ -300,7 +291,7 @@ namespace Masuit.Tools.Files
                     return false;
             }
 
-            return res;
+            return true;
         }
 
         #endregion
@@ -310,18 +301,18 @@ namespace Masuit.Tools.Files
         /// <summary>
         /// 压缩目录
         /// </summary>
-        /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
-        /// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
+        /// <param name="folderToZip">待压缩的文件夹,全路径格式</param>
+        /// <param name="zipedFile">压缩后的文件名,全路径格式</param>
         /// <param name="level">压缩等级</param>
-        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
+        private static bool ZipFileDictory(string folderToZip, string zipedFile, int level)
         {
             bool res;
-            if (!Directory.Exists(FolderToZip))
+            if (!Directory.Exists(folderToZip))
                 return false;
-            using (ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile)))
+            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipedFile)))
             {
                 s.SetLevel(level);
-                res = ZipFileDictory(FolderToZip, s, "");
+                res = ZipFileDictory(folderToZip, s, "");
                 s.Finish();
             }
             return res;
@@ -342,22 +333,21 @@ namespace Masuit.Tools.Files
         {
             if (!File.Exists(fileToZip))
                 throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
-            bool res = true;
-            FileStream ZipFile = File.OpenRead(fileToZip);
-            byte[] buffer = new byte[ZipFile.Length];
-            ZipFile.Read(buffer, 0, buffer.Length);
-            ZipFile = File.Create(zipedFile);
-            using (ZipFile)
+            FileStream zipFile = File.OpenRead(fileToZip);
+            byte[] buffer = new byte[zipFile.Length];
+            zipFile.Read(buffer, 0, buffer.Length);
+            zipFile = File.Create(zipedFile);
+            using (zipFile)
             {
-                using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
+                using (ZipOutputStream zipStream = new ZipOutputStream(zipFile))
                 {
                     var zipEntry = new ZipEntry(Path.GetFileName(fileToZip));
-                    ZipStream.PutNextEntry(zipEntry);
-                    ZipStream.SetLevel(level);
-                    ZipStream.Write(buffer, 0, buffer.Length);
+                    zipStream.PutNextEntry(zipEntry);
+                    zipStream.SetLevel(level);
+                    zipStream.Write(buffer, 0, buffer.Length);
                 }
             }
-            return res;
+            return true;
         }
 
         #endregion
@@ -380,20 +370,28 @@ namespace Masuit.Tools.Files
         /// <param name="dirpath">初始目录</param>
         public static void EnZip(string zipname, string zippath, string dirpath)
         {
-            the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
-            the_Obj = the_Reg.GetValue("");
-            the_rar = the_Obj.ToString();
-            the_Reg.Close();
-            the_rar = the_rar.Substring(1, the_rar.Length - 7);
-            the_Info = " a  " + zipname + " " + zippath;
-            the_StartInfo = new ProcessStartInfo();
-            the_StartInfo.FileName = the_rar;
-            the_StartInfo.Arguments = the_Info;
-            the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
-            the_StartInfo.WorkingDirectory = dirpath;
-            the_Process = new Process();
-            the_Process.StartInfo = the_StartInfo;
-            the_Process.Start();
+            _theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
+            if (_theReg != null)
+            {
+                _theObj = _theReg.GetValue("");
+                _theRar = _theObj.ToString();
+                _theReg?.Close();
+            }
+
+            _theRar = _theRar.Substring(1, _theRar.Length - 7);
+            _theInfo = " a  " + zipname + " " + zippath;
+            _theStartInfo = new ProcessStartInfo
+            {
+                FileName = _theRar,
+                Arguments = _theInfo,
+                WindowStyle = ProcessWindowStyle.Hidden,
+                WorkingDirectory = dirpath
+            };
+            _theProcess = new Process
+            {
+                StartInfo = _theStartInfo
+            };
+            _theProcess.Start();
         }
 
         #endregion
@@ -407,31 +405,39 @@ namespace Masuit.Tools.Files
         /// <param name="zippath">要解压的文件路径</param>
         public static void DeZip(string zipname, string zippath)
         {
-            the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
-            the_Obj = the_Reg.GetValue("");
-            the_rar = the_Obj.ToString();
-            the_Reg.Close();
-            the_rar = the_rar.Substring(1, the_rar.Length - 7);
-            the_Info = " X " + zipname + " " + zippath;
-            the_StartInfo = new ProcessStartInfo();
-            the_StartInfo.FileName = the_rar;
-            the_StartInfo.Arguments = the_Info;
-            the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
-            the_Process = new Process();
-            the_Process.StartInfo = the_StartInfo;
-            the_Process.Start();
+            _theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
+            if (_theReg != null)
+            {
+                _theObj = _theReg.GetValue("");
+                _theRar = _theObj.ToString();
+                _theReg.Close();
+            }
+
+            _theRar = _theRar.Substring(1, _theRar.Length - 7);
+            _theInfo = " X " + zipname + " " + zippath;
+            _theStartInfo = new ProcessStartInfo
+            {
+                FileName = _theRar,
+                Arguments = _theInfo,
+                WindowStyle = ProcessWindowStyle.Hidden
+            };
+            _theProcess = new Process
+            {
+                StartInfo = _theStartInfo
+            };
+            _theProcess.Start();
         }
 
         #endregion
 
         #region 私有变量
 
-        private static string the_rar;
-        private static RegistryKey the_Reg;
-        private static object the_Obj;
-        private static string the_Info;
-        private static ProcessStartInfo the_StartInfo;
-        private static Process the_Process;
+        private static string _theRar;
+        private static RegistryKey _theReg;
+        private static object _theObj;
+        private static string _theInfo;
+        private static ProcessStartInfo _theStartInfo;
+        private static Process _theProcess;
 
         #endregion
     }

+ 4 - 5
Masuit.Tools/Html/HtmlTools.cs

@@ -1135,7 +1135,6 @@ namespace Masuit.Tools.Html
             try
             {
                 Uri baseUri = new Uri(sUrl);
-
                 return baseUri.Scheme + "://" + baseUri.Authority;
             }
             catch
@@ -1304,7 +1303,7 @@ namespace Masuit.Tools.Html
                 }
                 catch (ArgumentException)
                 {//指定的编码不可识别
-                    content = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
+                    content = Encoding.GetEncoding("gb2312").GetString(buffer);
                 }
 
                 //content = CText.RemoveByReg(content, @"<!--[\s\S]*?-->");
@@ -1513,7 +1512,7 @@ ReCatch:
                         }
                         catch (Exception Ex)
                         {
-                            string str = Ex.Message;
+                            //string str = Ex.Message;
                             nBytes = -1;
                         }
                         if (nBytes <= 0) break;
@@ -1544,13 +1543,13 @@ ReCatch:
                     } while (nBytes > 0);
 
                     listResult.Add(new KeyValuePair<int, string>(kvUrl.Key, sbHtml.ToString()));
-                    sbHtml = null;
+                    //sbHtml = null;
                     sbHtml = new StringBuilder();
                 }
             }
             catch (Exception Ex)
             {
-                string s = Ex.Message;
+                //string s = Ex.Message;
                 try
                 {
                     sock.Shutdown(SocketShutdown.Both);

+ 1 - 0
Masuit.Tools/Logging/LogManager.cs

@@ -223,6 +223,7 @@ namespace Masuit.Tools.Logging
             }
             catch (Exception)
             {
+                // ignored
             }
         }
     }

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

@@ -115,6 +115,7 @@
     <Compile Include="Security\HashEncode.cs" />
     <Compile Include="Security\RSACrypt.cs" />
     <Compile Include="Systems\ConcurrentLimitedQueue.cs" />
+    <Compile Include="Systems\Disposable.cs" />
     <Compile Include="Systems\LimitedQueue.cs" />
     <Compile Include="Strings\ValidateCode.cs" />
     <Compile Include="Net\WebExtension.cs" />

+ 24 - 51
Masuit.Tools/Net/CookieHelper.cs

@@ -274,29 +274,23 @@ namespace Masuit.Tools.Net
         public static CookieCollection GetCK(string ck, string url)
         {
             CookieCollection cc = new CookieCollection();
-            string domain = "";
-            try
-            {
-                Uri u = new Uri(url);
-                domain = u.Host;
-            }
-            catch (Exception e)
-            {
-                LogManager.Error(e);
-            }
+            Uri u = new Uri(url);
+            var domain = u.Host;
             string[] cks = GetCKS(ck);
-            for (int i = 0; i < cks.Length; i++)
+            foreach (var t in cks)
             {
-                if (cks[i].IndexOf("=") > -1)
+                if (t.IndexOf("=") > -1)
                 {
                     try
                     {
-                        string n = cks[i].Substring(0, cks[i].IndexOf("="));
-                        string v = cks[i].Substring(cks[i].IndexOf("=") + 1);
-                        System.Net.Cookie c = new System.Net.Cookie();
-                        c.Name = n.Trim();
-                        c.Value = v.Trim();
-                        c.Domain = domain;
+                        string n = t.Substring(0, t.IndexOf("="));
+                        string v = t.Substring(t.IndexOf("=") + 1);
+                        Cookie c = new Cookie
+                        {
+                            Name = n.Trim(),
+                            Value = v.Trim(),
+                            Domain = domain
+                        };
                         cc.Add(c);
                     }
                     catch (Exception e)
@@ -354,24 +348,17 @@ namespace Masuit.Tools.Net
         /// <returns>Cookie集合中是否包含指定的Cookie</returns>
         public static async Task<bool> IncludeCKAsync(this List<string> cks, string ck)
         {
-            try
+            return await Task.Run(() =>
             {
-                return await Task.Run(() =>
+                foreach (string t in cks)
                 {
-                    foreach (string t in cks)
+                    if (t.ToLower().Trim().IndexOf(ck.Remove(ck.IndexOf('=') + 1).Trim().ToLower(), StringComparison.Ordinal) != -1)
                     {
-                        if (t.ToLower().Trim().IndexOf(ck.Remove(ck.IndexOf('=') + 1).Trim().ToLower(), StringComparison.Ordinal) != -1)
-                        {
-                            return true;
-                        }
+                        return true;
                     }
-                    return false;
-                }).ConfigureAwait(false);
-            }
-            catch (Exception)
-            {
+                }
                 return false;
-            }
+            }).ConfigureAwait(false);
         }
         #endregion
 
@@ -398,27 +385,13 @@ namespace Masuit.Tools.Net
         public static List<string> GetDomains(string url)
         {
             List<string> res = new List<string>();
-            try
-            {
-                url = url.Remove(url.IndexOf("?"));
-            }
-            catch (Exception e)
-            {
-                LogManager.Error(e);
-            }
-            try
-            {
-                Uri uri = new Uri(url);
-                string baseDomain = uri.Scheme + "://" + uri.Host;
-                for (int i = 0; i < uri.Segments.Length; i++)
-                {
-                    baseDomain += uri.Segments[i];
-                    res.Add(baseDomain);
-                }
-            }
-            catch (Exception e)
+            url = url.Remove(url.IndexOf("?"));
+            Uri uri = new Uri(url);
+            string baseDomain = uri.Scheme + "://" + uri.Host;
+            foreach (var t in uri.Segments)
             {
-                LogManager.Error(e);
+                baseDomain += t;
+                res.Add(baseDomain);
             }
             return res;
         }

+ 6 - 5
Masuit.Tools/NoSQL/RedisHelper.cs

@@ -4,6 +4,7 @@ using System.Collections.Generic;
 using System.Configuration;
 using System.Linq;
 using System.Threading.Tasks;
+using Masuit.Tools.Systems;
 using Newtonsoft.Json;
 using StackExchange.Redis;
 
@@ -12,10 +13,10 @@ namespace Masuit.Tools.NoSQL
     /// <summary>
     /// Redis操作
     /// </summary>
-    public class RedisHelper : IDisposable
+    public class RedisHelper : Disposable
     {
         private int DbNum { get; }
-        private readonly ConnectionMultiplexer _conn;
+        private ConnectionMultiplexer _conn;
 
         /// <summary>
         /// 自定义键
@@ -1253,10 +1254,10 @@ namespace Masuit.Tools.NoSQL
 
         #endregion 事件
 
-        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
-        public void Dispose()
+        public override void Dispose(bool disposing)
         {
-            _conn.Dispose();
+            _conn?.Dispose();
+            _conn = null;
         }
     }
 }

+ 2 - 2
Masuit.Tools/Properties/AssemblyInfo.cs

@@ -36,7 +36,7 @@ using System.Runtime.InteropServices;
 // 方法是按如下所示使用“*”: :
 // [assembly: AssemblyVersion("1.0.*")]
 
-[assembly: AssemblyVersion("1.9.6.0")]
-[assembly: AssemblyFileVersion("1.9.6.0")]
+[assembly: AssemblyVersion("1.9.7.0")]
+[assembly: AssemblyFileVersion("1.9.7.0")]
 [assembly: NeutralResourcesLanguage("zh-CN")]
 

+ 23 - 0
Masuit.Tools/Systems/Disposable.cs

@@ -0,0 +1,23 @@
+using System;
+
+namespace Masuit.Tools.Systems
+{
+    public abstract class Disposable : IDisposable
+    {
+        private bool isDisposed;
+
+        ~Disposable()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            isDisposed = true;
+            GC.SuppressFinalize(this);
+        }
+
+        public abstract void Dispose(bool disposing);
+    }
+}

+ 0 - 3
Masuit.Tools/Win32/Windows.cs

@@ -303,9 +303,6 @@ namespace Masuit.Tools.Win32
             {
                 return "unknow ";
             }
-            finally
-            {
-            }
         }
 
         string GetDiskID()

+ 7 - 5
Test/Program.cs

@@ -1,7 +1,8 @@
 using System;
 using System.Collections.Concurrent;
+using System.Net.Http;
+using System.Net.Http.Headers;
 using System.Threading.Tasks;
-using Masuit.Tools.NoSQL;
 
 namespace Test
 {
@@ -9,10 +10,11 @@ namespace Test
     {
         static void Main(string[] args)
         {
-            RedisHelper redisHelper = RedisHelper.GetInstance();
-            redisHelper.SetHash("test", "name", "zhangsan");
-            Console.WriteLine("ok");
-            Console.ReadKey();
+            var httpClient = new HttpClient() { BaseAddress = new Uri("http://www.hbtswl.com") };
+            httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0"));
+            var res = httpClient.GetAsync("/").Result;
+            var statusCode = res.StatusCode;
+            Console.WriteLine(statusCode);
         }
 
         public static ConcurrentDictionary<string, object> LockDic { get; set; } = new ConcurrentDictionary<string, object>();