瀏覽代碼

万年历实现

懒得勤快 6 年之前
父節點
當前提交
f51f442b10
共有 78 個文件被更改,包括 5752 次插入4731 次删除
  1. 4 1
      Masuit.Tools.Core/Database/DataExt.cs
  2. 62 35
      Masuit.Tools.Core/Database/DataTableHelper.cs
  3. 0 972
      Masuit.Tools.Core/DateTimeExt/CNCalendar.cs
  4. 1377 79
      Masuit.Tools.Core/DateTimeExt/ChineseCalendar.cs
  5. 18 0
      Masuit.Tools.Core/DateTimeExt/DateInfoStruct.cs
  6. 6 6
      Masuit.Tools.Core/DateTimeExt/DateTimeHelper.cs
  7. 5 1
      Masuit.Tools.Core/DateTimeExt/DateUtil.cs
  8. 25 43
      Masuit.Tools.Core/DateTimeExt/TimeHelper.cs
  9. 18 0
      Masuit.Tools.Core/DateTimeExt/WeekHolidayStruct.cs
  10. 3 8
      Masuit.Tools.Core/ExpressionGenericMapper.cs
  11. 179 399
      Masuit.Tools.Core/Extensions.cs
  12. 70 0
      Masuit.Tools.Core/Files/ExtensionAttach.cs
  13. 7 2
      Masuit.Tools.Core/Files/FileExt.cs
  14. 1 1
      Masuit.Tools.Core/Files/INIFile.cs
  15. 133 323
      Masuit.Tools.Core/Html/HtmlHelper.cs
  16. 181 257
      Masuit.Tools.Core/Html/HtmlTools.cs
  17. 1 1
      Masuit.Tools.Core/Logging/LogInfo.cs
  18. 1 1
      Masuit.Tools.Core/Logging/LogLevel.cs
  19. 51 37
      Masuit.Tools.Core/Logging/LogManager.cs
  20. 11 15
      Masuit.Tools.Core/Media/ImageUtilities.cs
  21. 27 1
      Masuit.Tools.Core/Net/FtpClient.cs
  22. 43 15
      Masuit.Tools.Core/Net/MultiThreadDownloader.cs
  23. 26 7
      Masuit.Tools.Core/Net/PartialDownloader.cs
  24. 20 11
      Masuit.Tools.Core/Net/SocketClient.cs
  25. 49 10
      Masuit.Tools.Core/Reflection/ReflectHelper.cs
  26. 43 26
      Masuit.Tools.Core/Reflection/ReflectionUtil.cs
  27. 332 248
      Masuit.Tools.Core/Security/Encrypt.cs
  28. 4 3
      Masuit.Tools.Core/Security/HashEncode.cs
  29. 6 1
      Masuit.Tools.Core/Security/RSACrypt.cs
  30. 32 0
      Masuit.Tools.Core/Strings/Template.cs
  31. 1 1
      Masuit.Tools.Core/Systems/ConcurrentLimitedQueue.cs
  32. 1 1
      Masuit.Tools.Core/Systems/Disposable.cs
  33. 34 5
      Masuit.Tools.Core/Systems/EnumExt.cs
  34. 1 1
      Masuit.Tools.Core/Systems/LimitedQueue.cs
  35. 1 1
      Masuit.Tools.Core/Systems/Lock.cs
  36. 38 22
      Masuit.Tools.Core/Systems/RedisLock.cs
  37. 3 1
      Masuit.Tools/Database/DataExt.cs
  38. 62 35
      Masuit.Tools/Database/DataTableHelper.cs
  39. 0 972
      Masuit.Tools/DateTimeExt/CNCalendar.cs
  40. 1461 79
      Masuit.Tools/DateTimeExt/ChineseCalendar.cs
  41. 18 0
      Masuit.Tools/DateTimeExt/DateInfoStruct.cs
  42. 6 6
      Masuit.Tools/DateTimeExt/DateTimeHelper.cs
  43. 4 0
      Masuit.Tools/DateTimeExt/DateUtil.cs
  44. 24 42
      Masuit.Tools/DateTimeExt/TimeHelper.cs
  45. 18 0
      Masuit.Tools/DateTimeExt/WeekHolidayStruct.cs
  46. 1 5
      Masuit.Tools/ExpressionGenericMapper.cs
  47. 54 16
      Masuit.Tools/Extensions.cs
  48. 22 3
      Masuit.Tools/Files/Compress.cs
  49. 9 7
      Masuit.Tools/Files/ExtensionAttach.cs
  50. 6 1
      Masuit.Tools/Files/FileExt.cs
  51. 1 1
      Masuit.Tools/Files/INIFile.cs
  52. 43 18
      Masuit.Tools/Hardware/SystemInfo.cs
  53. 132 322
      Masuit.Tools/Html/HtmlHelper.cs
  54. 184 229
      Masuit.Tools/Html/HtmlTools.cs
  55. 15 2
      Masuit.Tools/Logging/LogManager.cs
  56. 2 1
      Masuit.Tools/Masuit.Tools.csproj
  57. 10 13
      Masuit.Tools/Media/ImageUtilities.cs
  58. 24 21
      Masuit.Tools/Net/CacheHelper.cs
  59. 70 29
      Masuit.Tools/Net/CookieHelper.cs
  60. 27 1
      Masuit.Tools/Net/FtpClient.cs
  61. 42 14
      Masuit.Tools/Net/MultiThreadDownloader.cs
  62. 25 6
      Masuit.Tools/Net/PartialDownloader.cs
  63. 14 6
      Masuit.Tools/Net/SocketClient.cs
  64. 41 6
      Masuit.Tools/Net/WebExtension.cs
  65. 18 4
      Masuit.Tools/NoSQL/RedisHelper.cs
  66. 35 10
      Masuit.Tools/Reflection/ReflectHelper.cs
  67. 30 27
      Masuit.Tools/Reflection/ReflectionUtil.cs
  68. 331 246
      Masuit.Tools/Security/Encrypt.cs
  69. 4 3
      Masuit.Tools/Security/HashEncode.cs
  70. 6 1
      Masuit.Tools/Security/RSACrypt.cs
  71. 13 6
      Masuit.Tools/Strings/ValidateCode.cs
  72. 14 5
      Masuit.Tools/Systems/EnumExt.cs
  73. 34 9
      Masuit.Tools/Systems/RedisLock.cs
  74. 36 19
      Masuit.Tools/Win32/Windows.cs
  75. 3 1
      Masuit.Tools/Win32/WindowsCommand.cs
  76. 26 30
      Test/Program.cs
  77. 5 0
      Test/Test.csproj
  78. 68 0
      Test/Test.ruleset

+ 4 - 1
Masuit.Tools.Core/Database/DataExt.cs

@@ -3,7 +3,7 @@ using System.Data;
 using System.Data.SqlClient;
 using System.Reflection;
 
-namespace Masuit.Tools.Core.Database
+namespace Masuit.Tools.Database
 {
     /// <summary>
     /// SqlDataReader扩展类
@@ -25,6 +25,7 @@ namespace Masuit.Tools.Core.Database
             {
                 p.SetValue(obj, reader[p.Name]);
             }
+
             return obj;
         }
 
@@ -43,6 +44,7 @@ namespace Masuit.Tools.Core.Database
             {
                 p.SetValue(obj, row[p.Name]);
             }
+
             return obj;
         }
 
@@ -61,6 +63,7 @@ namespace Masuit.Tools.Core.Database
             {
                 p.SetValue(obj, dr[p.Name]);
             }
+
             return obj;
         }
     }

+ 62 - 35
Masuit.Tools.Core/Database/DataTableHelper.cs

@@ -28,6 +28,7 @@ namespace Masuit.Tools.Database
                     dt.Rows[i]["identityid"] = (i + 1).ToString();
                 }
             }
+
             return dt;
         }
 
@@ -36,12 +37,9 @@ namespace Masuit.Tools.Database
         /// </summary>
         /// <param name="dt">DataTable</param>
         /// <returns>是否有数据行</returns>
-        public static bool IsHaveRows(this DataTable dt)
+        public static bool HasRows(this DataTable dt)
         {
-            if (dt?.Rows.Count > 0)
-                return true;
-
-            return false;
+            return dt.Rows.Count > 0;
         }
 
         /// <summary>
@@ -52,8 +50,10 @@ namespace Masuit.Tools.Database
         /// <returns>强类型的数据集合</returns>
         public static IList<T> DataTableToList<T>(this DataTable table) where T : class
         {
-            if (!IsHaveRows(table))
+            if (!HasRows(table))
+            {
                 return new List<T>();
+            }
 
             IList<T> list = new List<T>();
             foreach (DataRow dr in table.Rows)
@@ -70,8 +70,10 @@ namespace Masuit.Tools.Database
                         pi.SetValue(model, drValue, null);
                     }
                 }
+
                 list.Add(model);
             }
+
             return list;
         }
 
@@ -88,6 +90,7 @@ namespace Masuit.Tools.Database
             {
                 return null;
             }
+
             var dt = new DataTable(typeof(T).Name);
             PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
             int length = myPropertyInfo.Length;
@@ -98,6 +101,7 @@ namespace Masuit.Tools.Database
                 {
                     continue;
                 }
+
                 var row = dt.NewRow();
                 for (int i = 0; i < length; i++)
                 {
@@ -108,14 +112,18 @@ namespace Masuit.Tools.Database
                         var column = new DataColumn(name, pi.PropertyType);
                         dt.Columns.Add(column);
                     }
+
                     row[name] = pi.GetValue(t, null);
                 }
+
                 if (createColumn)
                 {
                     createColumn = false;
                 }
+
                 dt.Rows.Add(row);
             }
+
             return dt;
         }
 
@@ -127,7 +135,7 @@ namespace Masuit.Tools.Database
         /// <returns>数据集(表)</returns>
         public static DataTable ToDataTable<T>(this IList<T> list)
         {
-            return ToDataTable<T>(list, null);
+            return ToDataTable(list, null);
         }
 
         /// <summary>
@@ -141,48 +149,55 @@ namespace Masuit.Tools.Database
         {
             List<string> propertyNameList = new List<string>();
             if (propertyName != null)
+            {
                 propertyNameList.AddRange(propertyName);
+            }
+
             DataTable result = new DataTable();
-            if (list.Count > 0)
+            if (list.Count <= 0)
+            {
+                return result;
+            }
+
+            PropertyInfo[] propertys = list[0].GetType().GetProperties();
+            propertys.ForEach(pi =>
             {
-                PropertyInfo[] propertys = list[0].GetType().GetProperties();
-                propertys.ForEach(pi =>
+                if (propertyNameList.Count == 0)
                 {
-                    if (propertyNameList.Count == 0)
+                    result.Columns.Add(pi.Name, pi.PropertyType);
+                }
+                else
+                {
+                    if (propertyNameList.Contains(pi.Name))
                     {
                         result.Columns.Add(pi.Name, pi.PropertyType);
                     }
-                    else
+                }
+            });
+            list.ForEach(item =>
+            {
+                ArrayList tempList = new ArrayList();
+                foreach (PropertyInfo pi in propertys)
+                {
+                    if (propertyNameList.Count == 0)
                     {
-                        if (propertyNameList.Contains(pi.Name))
-                        {
-                            result.Columns.Add(pi.Name, pi.PropertyType);
-                        }
+                        object obj = pi.GetValue(item, null);
+                        tempList.Add(obj);
                     }
-                });
-                list.ForEach(item =>
-                {
-                    ArrayList tempList = new ArrayList();
-                    foreach (PropertyInfo pi in propertys)
+                    else
                     {
-                        if (propertyNameList.Count == 0)
+                        if (propertyNameList.Contains(pi.Name))
                         {
                             object obj = pi.GetValue(item, null);
                             tempList.Add(obj);
                         }
-                        else
-                        {
-                            if (propertyNameList.Contains(pi.Name))
-                            {
-                                object obj = pi.GetValue(item, null);
-                                tempList.Add(obj);
-                            }
-                        }
                     }
-                    object[] array = tempList.ToArray();
-                    result.LoadDataRow(array, true);
-                });
-            }
+                }
+
+                object[] array = tempList.ToArray();
+                result.LoadDataRow(array, true);
+            });
+
             return result;
         }
 
@@ -194,12 +209,16 @@ namespace Masuit.Tools.Database
         public static DataTable CreateTable(this List<string> nameList)
         {
             if (nameList.Count <= 0)
+            {
                 return null;
+            }
+
             var myDataTable = new DataTable();
             foreach (string columnName in nameList)
             {
                 myDataTable.Columns.Add(columnName, typeof(string));
             }
+
             return myDataTable;
         }
 
@@ -229,6 +248,7 @@ namespace Masuit.Tools.Database
                     }
                 }
             }
+
             return dt;
         }
 
@@ -298,6 +318,7 @@ namespace Masuit.Tools.Database
                     newType = typeof(char);
                     break;
             }
+
             return newType;
         }
 
@@ -314,6 +335,7 @@ namespace Masuit.Tools.Database
             {
                 drs[i] = drc[i];
             }
+
             return drs;
         }
 
@@ -329,12 +351,14 @@ namespace Masuit.Tools.Database
             {
                 return new DataTable();
             }
+
             DataTable dt = rows[0].Table.Clone();
             dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
             for (int i = 0; i < rows.Length; i++)
             {
                 dt.LoadDataRow(rows[i].ItemArray, true);
             }
+
             return dt;
         }
 
@@ -353,8 +377,10 @@ namespace Masuit.Tools.Database
                 {
                     tmp += sorts[i] + ",";
                 }
+
                 dt.DefaultView.Sort = tmp.TrimEnd(',');
             }
+
             return dt;
         }
 
@@ -370,10 +396,11 @@ namespace Masuit.Tools.Database
             {
                 return dt;
             }
+
             var newdt = dt.Clone();
             DataRow[] dr = dt.Select(condition);
             dr.ForEach(t => newdt.ImportRow(t));
             return newdt;
         }
     }
-}
+}

+ 0 - 972
Masuit.Tools.Core/DateTimeExt/CNCalendar.cs

@@ -1,972 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-using System.Xml;
-
-namespace Masuit.Tools.DateTimeExt
-{
-    /// <summary>
-    /// 日历操作
-    /// </summary>
-    public static class CNCalendar
-    {
-        /// <summary>
-        /// 格式化日期
-        /// </summary>
-        /// <param name="m">月份</param>
-        /// <param name="d">日期</param>
-        /// <returns>x月x日</returns>
-        private static string FormatDate(int m, int d)
-        {
-            return $"{m:00}{d:00}";
-        }
-
-        /// <summary>
-        /// 从嵌入资源中读取文件内容(e.g: xml).
-        /// </summary>
-        /// <param name="fileWholeName">嵌入资源文件名,包括项目的命名空间.</param>
-        /// <returns>资源中的文件内容.</returns>
-        public static string ReadFileFromEmbedded(string fileWholeName)
-        {
-            //文件属性-生成操作-嵌入的资源
-            using (TextReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(fileWholeName)))
-            {
-                return reader.ReadToEnd();
-            }
-        }
-
-        #region 结构、日期对象
-
-        /// <summary>
-        /// 结构、日期对象
-        /// </summary>
-        private struct structDate
-        {
-            public int year;
-            public int month;
-            public int day;
-            public bool isLeap; //是否闰月
-            public int yearCyl; //年干支
-            public int monthCyl; //月干支
-            public int dayCyl; //日干支
-        }
-
-        #endregion
-
-        #region 结构、完整的日期对象
-
-        /// <summary>
-        /// 结构、完整的日期对象
-        /// </summary>
-        public struct StructDateFullInfo
-        {
-            /// <summary>
-            /// 公历年
-            /// </summary>
-            public int Year;
-
-            /// <summary>
-            /// 公历月
-            /// </summary>
-            public int Month;
-
-            /// <summary>
-            /// 公历日
-            /// </summary>
-            public int Day;
-
-            /// <summary>
-            /// 是否闰月
-            /// </summary>
-            public bool IsLeap; //是否闰月
-
-            /// <summary>
-            /// 农历年
-            /// </summary>
-            public int Cyear; //农历年
-
-            /// <summary>
-            /// 农历年名称
-            /// </summary>
-            public string Scyear; //农历年名称
-
-            /// <summary>
-            /// 干支年
-            /// </summary>
-            public string CyearCyl; //干支年
-
-            /// <summary>
-            /// 农历月
-            /// </summary>
-            public int Cmonth; //农历月
-
-            /// <summary>
-            /// 农历月名称
-            /// </summary>
-            public string Scmonth; //农历月名称
-
-            /// <summary>
-            /// 干支月
-            /// </summary>
-            public string CmonthCyl; //干支月
-
-            /// <summary>
-            /// 农历日
-            /// </summary>
-            public int Cday; //农历日
-
-            /// <summary>
-            /// 农历日名称
-            /// </summary>
-            public string Scday; //农历日名称
-
-            /// <summary>
-            /// 干支日
-            /// </summary>
-            public string CdayCyl; //干支日
-
-            /// <summary>
-            /// 农历属象
-            /// </summary>
-            public string cnAnm;
-
-            /// <summary>
-            /// 节气
-            /// </summary>
-            public string solarterm; //节气
-
-            /// <summary>
-            /// 星期几
-            /// </summary>
-            public string DayInWeek; //星期几
-
-            /// <summary>
-            /// 节日
-            /// </summary>
-            public string Feast; //节日
-
-            /// <summary>
-            /// 完整的日期信息
-            /// </summary>
-            public string Fullinfo; //完整的日期信息
-
-            /// <summary>
-            /// 阴历节日
-            /// </summary>
-            public string cnFtvl;
-
-            /// <summary>
-            /// 阳历节日
-            /// </summary>
-            public string cnFtvs;
-
-            /// <summary>
-            /// 系统问候语
-            /// </summary>
-            public string Info; //系统问候语
-
-            /// <summary>
-            /// 主题图片
-            /// </summary>
-            public string Image; //主题图片
-
-            /// <summary>
-            /// 有特别的问候语吗
-            /// </summary>
-            public bool SayHello; //有特别的问候语吗?
-        }
-
-        #endregion
-
-        #region 私有
-
-        #region  农历月份信息
-
-        /// <summary>
-        /// 农历月份信息
-        /// </summary>
-        private static readonly int[] lunarInfo =
-        {
-            0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
-            0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
-            0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
-            0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
-            0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
-            0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,
-            0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
-            0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
-            0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
-            0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
-            0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
-            0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
-            0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
-            0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
-            0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0
-        };
-
-        #endregion
-
-        /// <summary>
-        /// 农历月份名字
-        /// </summary>
-        private static readonly string[] cMonthName = { "", "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
-
-        //农历日子
-        private static readonly string[] nStr1 = { "日", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
-        private static readonly string[] nStr2 = { "初", "十", "廿", "卅", " " };
-        //公历月份名称
-        private static string[] monthName = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
-
-        /// <summary>
-        /// 天干
-        /// </summary>
-        private static readonly string[] gan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
-
-        /// <summary>
-        /// 地支
-        /// </summary>
-        private static readonly string[] zhi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
-
-        /// <summary>
-        /// 生肖
-        /// </summary>
-        private static readonly string[] animals
-            =
-            {
-                "鼠", "牛", "虎", "兔",
-                "龙", "蛇", "马", "羊",
-                "猴", "鸡", "狗", "猪"
-            };
-
-        /// <summary>
-        /// 节气
-        /// </summary>
-        private static readonly string[] solarTerm
-            =
-            {
-                "小寒", "大寒", "立春", "雨水",
-                "惊蛰", "春分", "清明", "谷雨",
-                "立夏", "小满", "芒种", "夏至",
-                "小暑", "大暑", "立秋", "处暑",
-                "白露", "秋分", "寒露", "霜降",
-                "立冬", "小雪", "大雪", "冬至"
-            };
-
-        /// <summary>
-        /// 节气对应数值?
-        /// </summary>
-        private static readonly int[] solarTermInfo =
-        {
-            0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072
-            , 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795
-            , 462224, 483532, 504758
-        };
-
-        #region 节日信息
-
-        private static readonly string[] lFtv = { "0101农历春节", "0202 龙抬头节", "0115 元宵节", "0505 端午节", "0707 七夕情人节", "0815 中秋节", "0909 重阳节", "1208 腊八节", "1114 李君先生生日", "1224 小年", "0100除夕" };
-        /// <summary>
-        /// 节假日信息
-        /// </summary>
-        private static readonly string[] sFtv =
-        {
-            "0101 新年元旦",
-            "0202 世界湿地日",
-            "0207 国际声援南非日",
-            "0210 国际气象节",
-            "0214 情人节",
-            "0301 国际海豹日",
-            "0303 全国爱耳日",
-            "0308 国际妇女节",
-            "0312 植树节 孙中山逝世纪念日",
-            "0314 国际警察日",
-            "0315 国际消费者权益日",
-            "0317 中国国医节 国际航海日",
-            "0321 世界森林日 消除种族歧视国际日",
-            "0321 世界儿歌日",
-            "0322 世界水日",
-            "0323 世界气象日",
-            "0324 世界防治结核病日",
-            "0325 全国中小学生安全教育日",
-            "0330 巴勒斯坦国土日",
-            "0401 愚人节 全国爱国卫生运动月(四月) 税收宣传月(四月)",
-            "0407 世界卫生日",
-            "0422 世界地球日",
-            "0423 世界图书和版权日",
-            "0424 亚非新闻工作者日",
-            "0501 国际劳动节",
-            "0504 中国五四青年节",
-            "0505 碘缺乏病防治日",
-            "0508 世界红十字日",
-            "0512 国际护士节",
-            "0515 国际家庭日",
-            "0517 世界电信日",
-            "0518 国际博物馆日",
-            "0520 全国学生营养日",
-            "0523 国际牛奶日",
-            "0531 世界无烟日",
-            "0601 国际儿童节",
-            "0605 世界环境日",
-            "0606 全国爱眼日",
-            "0617 防治荒漠化和干旱日",
-            "0623 国际奥林匹克日",
-            "0625 全国土地日",
-            "0626 国际反毒品日",
-            "0701 中国共产党建党日 世界建筑日",
-            "0702 国际体育记者日",
-            "0707 中国人民抗日战争纪念日",
-            "0711 世界人口日",
-            "0730 非洲妇女日",
-            "0801 中国建军节",
-            "0808 中国男子节(爸爸节)",
-            "0815 日本正式宣布无条件投降日",
-            "0908 国际扫盲日 国际新闻工作者日",
-            "0910 教师节",
-            "0914 世界清洁地球日",
-            "0916 国际臭氧层保护日",
-            "0918 九·一八事变纪念日",
-            "0920 全国爱牙日",
-            "0927 世界旅游日",
-            "1001 国庆节 世界音乐日 国际老人节",
-            "1001 国际音乐日",
-            "1002 国际和平与民主自由斗争日",
-            "1004 世界动物日",
-            "1008 全国高血压日",
-            "1008 世界视觉日",
-            "1009 世界邮政日 万国邮联日",
-            "1010 辛亥革命纪念日 世界精神卫生日",
-            "1013 世界保健日 国际教师节",
-            "1014 世界标准日",
-            "1015 国际盲人节(白手杖节)",
-            "1016 世界粮食日",
-            "1017 世界消除贫困日",
-            "1022 世界传统医药日",
-            "1024 联合国日 世界发展信息日",
-            "1031 世界勤俭日",
-            "1107 十月社会主义革命纪念日",
-            "1108 中国记者日",
-            "1109 全国消防安全宣传教育日",
-            "1110 世界青年节",
-            "1111 国际科学与和平周(本日所属的一周)",
-            "1112 孙中山诞辰纪念日",
-            "1114 世界糖尿病日",
-            "1117 国际大学生节 世界学生节",
-            "1121 世界问候日 世界电视日",
-            "1129 国际声援巴勒斯坦人民国际日",
-            "1201 世界艾滋病日",
-            "1203 世界残疾人日",
-            "1205 国际经济和社会发展志愿人员日",
-            "1208 国际儿童电视日",
-            "1209 世界足球日",
-            "1210 世界人权日",
-            "1212 西安事变纪念日",
-            "1213 南京大屠杀(1937年)纪念日!紧记血泪史!",
-            "1221 国际篮球日",
-            "1224 平安夜",
-            "1225 圣诞节",
-            "1226 毛主席诞辰",
-            "1229 国际生物多样性日"
-        };
-
-        #endregion
-
-        #endregion
-
-        #region 私有方法
-
-        /// <summary>
-        /// 传回农历y年的总天数
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static int GetLYearDays(int y)
-        {
-            int sum = 348;
-
-            for (int i = 0x8000; i > 0x8; i >>= 1)
-                sum += (lunarInfo[y - 1900] & i) > 0 ? 1 : 0;
-
-            return sum + GetLeapDays(y);
-        }
-
-        /// <summary>
-        /// 传回农历y年闰月的天数
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static int GetLeapDays(int y)
-        {
-            if (GetLeapMonth(y) > 0)
-                return (lunarInfo[y - 1900] & 0x10000) > 0 ? 30 : 29;
-            return 0;
-        }
-
-        /// <summary>
-        /// 传回农历y年闰哪个月 1-12 , 没闰传回 0
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static int GetLeapMonth(int y)
-        {
-            return lunarInfo[y - 1900] & 0xf;
-        }
-
-        /// <summary>
-        /// 传回农历y年m月的总天数
-        /// </summary>
-        /// <param name="y">公元年</param>
-        /// <param name="m">月份</param> 
-        private static int GetLMonthDays(int y, int m)
-        {
-            return (lunarInfo[y - 1900] & (0x10000 >> m)) > 0 ? 30 : 29;
-        }
-
-        /// <summary>
-        /// 传回农历y年的生肖
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static string AnimalsYear(int y)
-        {
-            return animals[(y - 4) % 12];
-        }
-
-        /// <summary>
-        ///传入月日的offset 传回天干地支, 0=甲子
-        /// </summary>
-        /// <param name="num">月日的偏差</param>
-        private static string Cyclical(int num)
-        {
-            return gan[num % 10] + zhi[num % 12];
-        }
-
-        /// <summary>
-        /// 传入offset 传回干支, 0=甲子
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static string cyclical(int y)
-        {
-            int num = y - 1900 + 36;
-            return Cyclical(num);
-        }
-
-        #region 得到农历日期、年月日的天干地址及是否闰月
-
-        #region  返回一个农历日期结构体
-
-        /// <summary>
-        /// 返回一个农历日期结构体
-        /// </summary>
-        /// <param name="date">日期对象</param>
-        /// <returns>农历日期结构体</returns>
-        private static structDate GetLunar(DateTime date)
-        {
-            structDate sd;
-
-            int i = 0, leap = 0, temp = 0;
-            DateTime baseDate = new DateTime(1900, 1, 31); //基准时间
-
-            int offset = (date - baseDate).Days; //与基准时间相隔天数
-
-            sd.dayCyl = offset + 40;
-            sd.monthCyl = 14;
-
-            for (i = 1900; (i < 2050) && (offset > 0); i++)
-            {
-                temp = GetLYearDays(i);
-                offset -= temp;
-                sd.monthCyl += 12;
-            }
-            if (offset < 0)
-            {
-                offset += temp;
-                i--;
-                sd.monthCyl -= 12;
-            }
-
-            sd.year = i;
-            sd.yearCyl = i - 1864;
-
-            //闰哪个月
-            leap = GetLeapMonth(i);
-            sd.isLeap = false;
-            for (i = 1; (i < 13) && (offset > 0); i++)
-            {
-                //闰月 
-                if ((leap > 0) && (i == leap + 1) && (!sd.isLeap))
-                {
-                    --i;
-                    sd.isLeap = true;
-                    temp = GetLeapDays(sd.year);
-                }
-                else
-                {
-                    temp = GetLMonthDays(sd.year, i);
-                }
-                //解除闰月 
-                if (sd.isLeap && (i == leap + 1))
-                    sd.isLeap = false;
-                offset -= temp;
-                if (!sd.isLeap)
-                    sd.monthCyl++;
-            }
-            if ((offset == 0) && (leap > 0) && (i == leap + 1))
-            {
-                if (sd.isLeap)
-                {
-                    sd.isLeap = false;
-                }
-                else
-                {
-                    sd.isLeap = true;
-                    --i;
-                    --sd.monthCyl;
-                }
-            }
-
-            if (offset < 0)
-            {
-                offset += temp;
-                --i;
-                --sd.monthCyl;
-            }
-
-            sd.month = i;
-            sd.day = offset + 1;
-
-            return sd;
-        }
-
-        #endregion
-
-        #region 传出y年m月d日对应的农历 [0].year [1].month [2].day2 [3].yearCyl [4].monCyl [5].dayCyl [6].isLeap
-
-        /// <summary>
-        /// 传出y年m月d日对应的农历[0].year [1].month [2].day2 [3].yearCyl [4].monCyl [5].dayCyl [6].isLeap
-        /// </summary>
-        /// <param name="y">年</param>
-        /// <param name="m">月</param>
-        /// <param name="d">日</param>
-        private static long[] calElement(int y, int m, int d)
-        {
-            long[] nongDate = new long[7];
-
-            int i = 0, temp = 0, leap = 0;
-            DateTime baseDate = new DateTime(1900, 1, 31);
-
-            DateTime objDate = new DateTime(y, m, d);
-            TimeSpan ts = objDate - baseDate;
-
-            long offset = (long)ts.TotalDays;
-            nongDate[5] = offset + 40;
-            nongDate[4] = 14;
-
-            for (i = 1900; (i < 2050) && (offset > 0); i++)
-            {
-                temp = GetLYearDays(i);
-                offset -= temp;
-                nongDate[4] += 12;
-            }
-            if (offset < 0)
-            {
-                offset += temp;
-                i--;
-                nongDate[4] -= 12;
-            }
-            nongDate[0] = i;
-            nongDate[3] = i - 1864;
-            leap = GetLeapMonth(i); // 闰哪个月
-            nongDate[6] = 0;
-
-            for (i = 1; (i < 13) && (offset > 0); i++)
-            {
-                // 闰月
-                if ((leap > 0) && (i == leap + 1) && (nongDate[6] == 0))
-                {
-                    --i;
-                    nongDate[6] = 1;
-                    temp = GetLeapDays((int)nongDate[0]);
-                }
-                else
-                {
-                    temp = GetLMonthDays((int)nongDate[0], i);
-                }
-
-                // 解除闰月
-                if ((nongDate[6] == 1) && (i == leap + 1))
-                    nongDate[6] = 0;
-                offset -= temp;
-                if (nongDate[6] == 0)
-                    nongDate[4]++;
-            }
-
-            if ((offset == 0) && (leap > 0) && (i == leap + 1))
-            {
-                if (nongDate[6] == 1)
-                {
-                    nongDate[6] = 0;
-                }
-                else
-                {
-                    nongDate[6] = 1;
-                    --i;
-                    --nongDate[4];
-                }
-            }
-
-            if (offset < 0)
-            {
-                offset += temp;
-                --i;
-                --nongDate[4];
-            }
-            nongDate[1] = i;
-            nongDate[2] = offset + 1;
-            return nongDate;
-        }
-
-        #endregion
-
-        #endregion
-
-        /// <summary>
-        /// 将值转成农历汉字日子
-        /// </summary>
-        /// <param name="d">农历日</param>
-        /// <returns>中文表示</returns>
-        private static string GetCDay(int d)
-        {
-            string s = "";
-
-            switch (d)
-            {
-                case 10:
-                    s = "初十";
-                    break;
-                case 20:
-                    s = "二十";
-                    break;
-                case 30:
-                    s = "三十";
-                    break;
-                default:
-                    s = nStr2[(int)Math.Floor((double)d / 10)];
-                    s += nStr1[d % 10];
-                    break;
-            }
-            return s;
-        }
-
-        /// <summary>
-        ///  某年的第n个节气为几日(从0,即小寒起算)
-        ///	n:节气下标
-        /// </summary>
-        /// <param name="y">年</param>
-        /// <param name="n">节气</param>
-        /// <returns>日期时间</returns>
-        private static DateTime GetSolarTermDay(int y, int n)
-        {
-            //按分钟起计算
-            double minutes = (525948.766245 * (y - 1900)) + solarTermInfo[n - 1];
-            //1900年1月6日:小寒 
-            DateTime baseDate = new DateTime(1900, 1, 6, 2, 5, 0);
-            DateTime veryDate = baseDate.AddMinutes(minutes);
-            return veryDate;
-            //按毫秒起计算
-            //double ms = 31556925974.7 * (y - 1900);
-            // double ms1 = solarTermInfo[n];
-            // DateTime baseDate = new DateTime(1900, 1, 6, 2, 5, 0);
-            // baseDate = baseDate.AddMilliseconds(ms);
-            // baseDate = baseDate.AddMinutes(ms1);
-        }
-
-        #endregion
-
-        #region 公有方法
-
-        #region 得到精简日期信息(不含节日)
-
-        /// <summary>
-        /// 得到精简日期信息(不含节日)
-        /// </summary>
-        /// <param name="d">待检查的日子</param>
-        /// <returns>日期信息</returns>
-        public static StructDateFullInfo GetDateTidyInfo(this DateTime d)
-        {
-            var dayinfo = new StructDateFullInfo();
-            structDate day = GetLunar(d);
-            dayinfo.IsLeap = day.isLeap;
-            dayinfo.Year = d.Year;
-            dayinfo.Cyear = day.year;
-            dayinfo.Scyear = animals[(day.year - 4) % 12];
-            dayinfo.CyearCyl = Cyclical(day.yearCyl); //干支年
-            dayinfo.Month = d.Month;
-            dayinfo.Cmonth = day.month;
-            dayinfo.Scmonth = cMonthName[day.month];
-            dayinfo.CmonthCyl = Cyclical(day.monthCyl); //干支月
-            dayinfo.Day = d.Day;
-            dayinfo.Cday = day.day;
-            dayinfo.Scday = GetCDay(day.day); //日子
-            dayinfo.CdayCyl = Cyclical(day.dayCyl); //干支日
-            switch (d.DayOfWeek)
-            {
-                case DayOfWeek.Sunday:
-                    dayinfo.DayInWeek = "星期日";
-                    break;
-                case DayOfWeek.Monday:
-                    dayinfo.DayInWeek = "星期一";
-                    break;
-                case DayOfWeek.Tuesday:
-                    dayinfo.DayInWeek = "星期二";
-                    break;
-                case DayOfWeek.Wednesday:
-                    dayinfo.DayInWeek = "星期三";
-                    break;
-                case DayOfWeek.Thursday:
-                    dayinfo.DayInWeek = "星期四";
-                    break;
-                case DayOfWeek.Friday:
-                    dayinfo.DayInWeek = "星期五";
-                    break;
-                case DayOfWeek.Saturday:
-                    dayinfo.DayInWeek = "星期六";
-                    break;
-                default:
-                    dayinfo.DayInWeek = "星期?";
-                    break;
-            }
-
-            dayinfo.Info = "";
-            dayinfo.Feast = "";
-            dayinfo.Image = "";
-            dayinfo.SayHello = false;
-
-            //节气
-            //每个月有两个节气
-            int d1 = GetSolarTermDay(d.Year, (d.Month * 2) - 1).Day;
-            int d2 = GetSolarTermDay(d.Year, d.Month * 2).Day;
-            if (dayinfo.Day == d1)
-            {
-                if (solarTerm.Length > d.Month * 2 - 2) dayinfo.solarterm = solarTerm[d.Month * 2 - 2];
-            }
-            else if (dayinfo.Day == d2)
-            {
-                dayinfo.solarterm = solarTerm[d.Month * 2 - 1];
-            }
-            else
-            {
-                dayinfo.solarterm = "";
-            }
-
-            dayinfo.Fullinfo = dayinfo.Year + "年" + dayinfo.Month + "月" + dayinfo.Day + "日";
-            dayinfo.Fullinfo += " " + dayinfo.DayInWeek;
-            dayinfo.Fullinfo += " 农历" + dayinfo.CyearCyl + "(" + dayinfo.Scyear + ")年";
-            if (dayinfo.IsLeap)
-                dayinfo.Fullinfo += "闰";
-            dayinfo.Fullinfo += dayinfo.Scmonth + dayinfo.Scday;
-            if (dayinfo.solarterm != "")
-                dayinfo.Fullinfo += " " + dayinfo.solarterm;
-
-            return dayinfo;
-        }
-
-        #endregion
-
-        #region    得到日期信息
-
-        /// <summary>
-        /// 得到日期信息
-        /// </summary>
-        /// <param name="d">待检查的日子</param>
-        /// <returns>日期信息</returns>
-        public static StructDateFullInfo GetDateInfo(this DateTime d)
-        {
-            // xml文件属性-生成操作-嵌入的资源
-            string calendarXmlData = ReadFileFromEmbedded("Core.Common" + "CCalendarData.xml");
-
-            StructDateFullInfo dayinfo = new StructDateFullInfo();
-            structDate day = GetLunar(d);
-
-            dayinfo.IsLeap = day.isLeap;
-
-            dayinfo.Year = d.Year;
-            dayinfo.Cyear = day.year;
-            dayinfo.Scyear = animals[(day.year - 4) % 12];
-            dayinfo.CyearCyl = Cyclical(day.yearCyl); //干支年
-
-            dayinfo.Month = d.Month;
-            dayinfo.Cmonth = day.month;
-            dayinfo.Scmonth = cMonthName[day.month];
-            dayinfo.CmonthCyl = Cyclical(day.monthCyl); //干支月
-
-            dayinfo.Day = d.Day;
-            dayinfo.Cday = day.day;
-            dayinfo.Scday = GetCDay(day.day); //日子
-            dayinfo.CdayCyl = Cyclical(day.dayCyl); //干支日
-
-            switch (d.DayOfWeek)
-            {
-                case DayOfWeek.Sunday:
-                    dayinfo.DayInWeek = "星期日";
-                    break;
-                case DayOfWeek.Monday:
-                    dayinfo.DayInWeek = "星期一";
-                    break;
-                case DayOfWeek.Tuesday:
-                    dayinfo.DayInWeek = "星期二";
-                    break;
-                case DayOfWeek.Wednesday:
-                    dayinfo.DayInWeek = "星期三";
-                    break;
-                case DayOfWeek.Thursday:
-                    dayinfo.DayInWeek = "星期四";
-                    break;
-                case DayOfWeek.Friday:
-                    dayinfo.DayInWeek = "星期五";
-                    break;
-                case DayOfWeek.Saturday:
-                    dayinfo.DayInWeek = "星期六";
-                    break;
-                default:
-                    dayinfo.DayInWeek = "星期?";
-                    break;
-            }
-
-            //节气
-            //每个月有两个节气
-            int d1 = GetSolarTermDay(d.Year, d.Month * 2 - 1).Day;
-            int d2 = GetSolarTermDay(d.Year, d.Month * 2).Day;
-            if (dayinfo.Day == d1)
-                dayinfo.solarterm = solarTerm[d.Month * 2 - 2];
-            else if (dayinfo.Day == d2)
-                dayinfo.solarterm = solarTerm[d.Month * 2 - 1];
-            else
-                dayinfo.solarterm = "";
-
-            //节日及问候语
-            dayinfo.Info = "";
-            dayinfo.Feast = "";
-            dayinfo.Image = "";
-            dayinfo.SayHello = false;
-            XmlDocument feastdoc = new XmlDocument();
-            feastdoc.LoadXml(calendarXmlData);
-
-            //公历
-            XmlNodeList nodeList = feastdoc.SelectNodes("descendant::AD/feast[@day='" + d.ToString("MMdd") + "']");
-            foreach (XmlNode root in nodeList)
-            {
-                dayinfo.Feast += root.Attributes["name"].InnerText + " ";
-                if (root.Attributes["sayhello"].InnerText == "yes")
-                {
-                    //需要显示节日问候语
-                    dayinfo.Info = root["hello"].InnerText;
-                    //看看是否需要计算周年
-                    if (root["startyear"] != null)
-                    {
-                        int startyear = Convert.ToInt32(root["startyear"].InnerText);
-                        dayinfo.Info = dayinfo.Info.Replace("_YEARS_", (d.Year - startyear).ToString());
-                    }
-                    dayinfo.Image = root["img"].InnerText;
-                    dayinfo.SayHello = true;
-                }
-            }
-
-            //农历
-            string smmdd = "";
-            smmdd = dayinfo.Cmonth.ToString().Length == 2 ? dayinfo.Cmonth.ToString() : "0" + dayinfo.Cmonth;
-            smmdd += dayinfo.Cday.ToString().Length == 2 ? dayinfo.Cday.ToString() : "0" + dayinfo.Cday;
-            XmlNode feast = feastdoc.SelectSingleNode("descendant::LUNAR/feast[@day='" + smmdd + "']");
-            if (feast != null)
-            {
-                dayinfo.Feast += feast.Attributes["name"].InnerText;
-
-                if (feast.Attributes["sayhello"].InnerText == "yes")
-                {
-                    //需要显示节日问候语
-                    dayinfo.Info += feast["hello"].InnerText;
-                    dayinfo.Image = feast["img"].InnerText;
-                    dayinfo.SayHello = true;
-                }
-            }
-            //普通日子或没有庆贺语
-            if (dayinfo.Info?.Length == 0)
-            {
-                feast = feastdoc.SelectSingleNode("descendant::NORMAL/day[@time1<'" + d.ToString("HHmm") + "']");
-                if (feast != null)
-                {
-                    dayinfo.Info = feast["hello"].InnerText;
-                    dayinfo.Image = feast["img"].InnerText;
-                }
-            }
-
-            dayinfo.Fullinfo = dayinfo.Year + "年" + dayinfo.Month + "月" + dayinfo.Day + "日";
-            dayinfo.Fullinfo += dayinfo.DayInWeek;
-            dayinfo.Fullinfo += " 农历" + dayinfo.CyearCyl + "[" + dayinfo.Scyear + "]年";
-            if (dayinfo.IsLeap)
-                dayinfo.Fullinfo += "闰";
-            dayinfo.Fullinfo += dayinfo.Scmonth + dayinfo.Scday;
-            if (dayinfo.solarterm != "")
-                dayinfo.Fullinfo += "  " + dayinfo.solarterm;
-
-            return dayinfo;
-        }
-
-        #endregion
-
-        /// <summary>
-        /// 获取农历
-        /// </summary>
-        /// <param name="dt">阳历日期</param>
-        public static StructDateFullInfo getChinaDate(this DateTime dt)
-        {
-            StructDateFullInfo cd = new StructDateFullInfo();
-            int year = dt.Year;
-            int month = dt.Month;
-            int date = dt.Day;
-            long[] l = calElement(year, month, date);
-            cd.Cyear = (int)l[0];
-            cd.Cmonth = (int)l[1];
-            cd.Cday = (int)l[2];
-            cd.Scyear = cyclical(year);
-            cd.cnAnm = AnimalsYear(year);
-            cd.Scmonth = nStr1[(int)l[1]];
-            cd.Scday = GetCDay((int)l[2]);
-            string smd = dt.ToString("MMdd");
-
-            string lmd = FormatDate(cd.Cmonth, cd.Cday);
-            for (int i = 0; i < solarTerm.Length; i++)
-            {
-                string s1 = GetSolarTermDay(dt.Year, i).ToString("MMdd");
-                if (s1.Equals(dt.ToString("MMdd")))
-                {
-                    cd.solarterm = solarTerm[i];
-                    break;
-                }
-            }
-            foreach (string s in sFtv)
-            {
-                string s1 = s.Substring(0, 4);
-                if (s1.Equals(smd))
-                {
-                    cd.cnFtvs = s.Substring(4, s.Length - 4);
-                    break;
-                }
-            }
-            foreach (string s in lFtv)
-            {
-                string s1 = s.Substring(0, 4);
-                if (s1.Equals(lmd))
-                {
-                    cd.cnFtvl = s.Substring(4, s.Length - 4);
-                    break;
-                }
-            }
-            dt = dt.AddDays(1);
-            year = dt.Year;
-            month = dt.Month;
-            date = dt.Day;
-            l = calElement(year, month, date);
-            lmd = FormatDate((int)l[1], (int)l[2]);
-            if (lmd.Equals("0101")) cd.cnFtvl = "除夕";
-            return cd;
-        }
-
-        #endregion
-    }
-}

+ 1377 - 79
Masuit.Tools.Core/DateTimeExt/ChineseCalendar.cs

@@ -1,162 +1,1460 @@
 using System;
-using System.Globalization;
+using System.Collections.Generic;
+using System.Linq;
 
 namespace Masuit.Tools.DateTimeExt
 {
     /// <summary>
-    /// 中国农历年处理类用net自带类
+    /// 中国农历类 支持 1900.1.31日起至 2069.12.31日止的数据
     /// </summary>
-    public static class ChineseCalendar
+    /// <remarks>
+    /// 本程序使用数据来源于网上的万年历查询,并综合了一些其它数据
+    /// </remarks>
+    public class ChineseCalendar
     {
+        private class ChineseCalendarException : Exception
+        {
+            public ChineseCalendarException(string msg) : base(msg)
+            {
+            }
+        }
+
+        #region 内部变量
+
+        private DateTime _date;
+        private readonly DateTime _datetime;
+        private readonly int _cYear;
+        private readonly int _cMonth;
+        private readonly int _cDay;
+        private readonly bool _cIsLeapMonth; //当月是否闰月
+        private readonly bool _cIsLeapYear; //当年是否有闰月
+
+        #endregion
+
+        #region 基础数据
+
+        private const int MinYear = 1900;
+        private const int MaxYear = 2050;
+        private static readonly DateTime MinDay = new DateTime(1900, 1, 30);
+        private static readonly DateTime MaxDay = new DateTime(2069, 12, 31);
+        private const int GanZhiStartYear = 1864; //干支计算起始年
+        private static readonly DateTime GanZhiStartDay = new DateTime(1899, 12, 22); //起始日
+        private const string HzNum = "零一二三四五六七八九";
+        private const int AnimalStartYear = 1900; //1900年为鼠年
+        private static readonly DateTime ChineseConstellationReferDay = new DateTime(2007, 9, 13); //28星宿参考值,本日为角
+
+        /// <summary>
+        /// 来源于网上的农历数据
+        /// </summary>
+        /// <remarks>
+        /// 数据结构如下,共使用17位数据
+        /// 第17位:表示闰月天数,0表示29天   1表示30天
+        /// 第16位-第5位(共12位)表示12个月,其中第16位表示第一月,如果该月为30天则为1,29天为0
+        /// 第4位-第1位(共4位)表示闰月是哪个月,如果当年没有闰月,则置0
+        ///</remarks>
+        private static readonly int[] LunarDateArray =
+        {
+            0x04BD8,
+            0x04AE0,
+            0x0A570,
+            0x054D5,
+            0x0D260,
+            0x0D950,
+            0x16554,
+            0x056A0,
+            0x09AD0,
+            0x055D2,
+            0x04AE0,
+            0x0A5B6,
+            0x0A4D0,
+            0x0D250,
+            0x1D255,
+            0x0B540,
+            0x0D6A0,
+            0x0ADA2,
+            0x095B0,
+            0x14977,
+            0x04970,
+            0x0A4B0,
+            0x0B4B5,
+            0x06A50,
+            0x06D40,
+            0x1AB54,
+            0x02B60,
+            0x09570,
+            0x052F2,
+            0x04970,
+            0x06566,
+            0x0D4A0,
+            0x0EA50,
+            0x06E95,
+            0x05AD0,
+            0x02B60,
+            0x186E3,
+            0x092E0,
+            0x1C8D7,
+            0x0C950,
+            0x0D4A0,
+            0x1D8A6,
+            0x0B550,
+            0x056A0,
+            0x1A5B4,
+            0x025D0,
+            0x092D0,
+            0x0D2B2,
+            0x0A950,
+            0x0B557,
+            0x06CA0,
+            0x0B550,
+            0x15355,
+            0x04DA0,
+            0x0A5B0,
+            0x14573,
+            0x052B0,
+            0x0A9A8,
+            0x0E950,
+            0x06AA0,
+            0x0AEA6,
+            0x0AB50,
+            0x04B60,
+            0x0AAE4,
+            0x0A570,
+            0x05260,
+            0x0F263,
+            0x0D950,
+            0x05B57,
+            0x056A0,
+            0x096D0,
+            0x04DD5,
+            0x04AD0,
+            0x0A4D0,
+            0x0D4D4,
+            0x0D250,
+            0x0D558,
+            0x0B540,
+            0x0B6A0,
+            0x195A6,
+            0x095B0,
+            0x049B0,
+            0x0A974,
+            0x0A4B0,
+            0x0B27A,
+            0x06A50,
+            0x06D40,
+            0x0AF46,
+            0x0AB60,
+            0x09570,
+            0x04AF5,
+            0x04970,
+            0x064B0,
+            0x074A3,
+            0x0EA50,
+            0x06B58,
+            0x055C0,
+            0x0AB60,
+            0x096D5,
+            0x092E0,
+            0x0C960,
+            0x0D954,
+            0x0D4A0,
+            0x0DA50,
+            0x07552,
+            0x056A0,
+            0x0ABB7,
+            0x025D0,
+            0x092D0,
+            0x0CAB5,
+            0x0A950,
+            0x0B4A0,
+            0x0BAA4,
+            0x0AD50,
+            0x055D9,
+            0x04BA0,
+            0x0A5B0,
+            0x15176,
+            0x052B0,
+            0x0A930,
+            0x07954,
+            0x06AA0,
+            0x0AD50,
+            0x05B52,
+            0x04B60,
+            0x0A6E6,
+            0x0A4E0,
+            0x0D260,
+            0x0EA65,
+            0x0D530,
+            0x05AA0,
+            0x076A3,
+            0x096D0,
+            0x04BD7,
+            0x04AD0,
+            0x0A4D0,
+            0x1D0B6,
+            0x0D250,
+            0x0D520,
+            0x0DD45,
+            0x0B5A0,
+            0x056D0,
+            0x055B2,
+            0x049B0,
+            0x0A577,
+            0x0A4B0,
+            0x0AA50,
+            0x1B255,
+            0x06D20,
+            0x0ADA0,
+            0x14B63
+        };
+
         /// <summary>
-        /// 实例化一个  ChineseLunisolarCalendar
+        /// 星座
         /// </summary>
-        private static ChineseLunisolarCalendar cCalendar = new ChineseLunisolarCalendar();
+        private static readonly string[] ConstellationName =
+        {
+            "白羊座",
+            "金牛座",
+            "双子座",
+            "巨蟹座",
+            "狮子座",
+            "处女座",
+            "天秤座",
+            "天蝎座",
+            "射手座",
+            "摩羯座",
+            "水瓶座",
+            "双鱼座"
+        };
 
         /// <summary>
-        /// 获取农历当前日期
+        /// 二十四节气
         /// </summary>
-        /// <returns>当前农历日期</returns>
-        public static string GetChineseDateTimeNow(this DateTime dt) => GetChineseDateTime(dt);
+        private static readonly string[] LunarHolidayName =
+        {
+            "小寒",
+            "大寒",
+            "立春",
+            "雨水",
+            "惊蛰",
+            "春分",
+            "清明",
+            "谷雨",
+            "立夏",
+            "小满",
+            "芒种",
+            "夏至",
+            "小暑",
+            "大暑",
+            "立秋",
+            "处暑",
+            "白露",
+            "秋分",
+            "寒露",
+            "霜降",
+            "立冬",
+            "小雪",
+            "大雪",
+            "冬至"
+        };
 
         /// <summary>
-        /// 根据公历获取农历日期
+        /// 二十八星宿
         /// </summary>
-        /// <param name="datetime">公历日期</param>
-        /// <returns>公历日期的字符串形式</returns>
-        public static string GetChineseDateTime(this DateTime datetime)
+        private static readonly string[] ChineseConstellationName =
         {
-            int lyear = cCalendar.GetYear(datetime);
-            int lmonth = cCalendar.GetMonth(datetime);
-            int lday = cCalendar.GetDayOfMonth(datetime);
-            //获取闰月, 0 则表示没有闰月
-            int leapMonth = cCalendar.GetLeapMonth(lyear);
-            bool isleap = false;
-            if (leapMonth > 0)
+            //四        五      六         日        一      二      三  
+            "角木蛟",
+            "亢金龙",
+            "女土蝠",
+            "房日兔",
+            "心月狐",
+            "尾火虎",
+            "箕水豹",
+            "斗木獬",
+            "牛金牛",
+            "氐土貉",
+            "虚日鼠",
+            "危月燕",
+            "室火猪",
+            "壁水獝",
+            "奎木狼",
+            "娄金狗",
+            "胃土彘",
+            "昴日鸡",
+            "毕月乌",
+            "觜火猴",
+            "参水猿",
+            "井木犴",
+            "鬼金羊",
+            "柳土獐",
+            "星日马",
+            "张月鹿",
+            "翼火蛇",
+            "轸水蚓"
+        };
+
+        #region 节气数据
+
+        /// <summary>
+        /// 节气数据
+        /// </summary>
+        private static readonly string[] SolarTerm =
+        {
+            "小寒",
+            "大寒",
+            "立春",
+            "雨水",
+            "惊蛰",
+            "春分",
+            "清明",
+            "谷雨",
+            "立夏",
+            "小满",
+            "芒种",
+            "夏至",
+            "小暑",
+            "大暑",
+            "立秋",
+            "处暑",
+            "白露",
+            "秋分",
+            "寒露",
+            "霜降",
+            "立冬",
+            "小雪",
+            "大雪",
+            "冬至"
+        };
+
+        private static readonly int[] STermInfo =
+        {
+            0,
+            21208,
+            42467,
+            63836,
+            85337,
+            107014,
+            128867,
+            150921,
+            173149,
+            195551,
+            218072,
+            240693,
+            263343,
+            285989,
+            308563,
+            331033,
+            353350,
+            375494,
+            397447,
+            419210,
+            440795,
+            462224,
+            483532,
+            504758
+        };
+
+        #endregion
+
+        #region 农历相关数据
+
+        private const string GanStr = "甲乙丙丁戊己庚辛壬癸";
+        private const string ZhiStr = "子丑寅卯辰巳午未申酉戌亥";
+        private const string AnimalStr = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
+        private const string NStr1 = "日一二三四五六七八九";
+        private const string NStr2 = "初十廿卅";
+
+        private static readonly string[] MonthString =
+        {
+            "出错",
+            "正月",
+            "二月",
+            "三月",
+            "四月",
+            "五月",
+            "六月",
+            "七月",
+            "八月",
+            "九月",
+            "十月",
+            "十一月",
+            "腊月"
+        };
+
+        #endregion
+
+        #region 节日数据
+        /// <summary>
+        /// 按公历计算的节日
+        /// </summary>
+        public static HashSet<DateInfoStruct> SolarHolidayInfo { get; } = new HashSet<DateInfoStruct>
+        {
+            new DateInfoStruct(1, 1, 1, "元旦"),
+            new DateInfoStruct(2, 2, 0, "世界湿地日"),
+            new DateInfoStruct(2, 10, 0, "国际气象节"),
+            new DateInfoStruct(2, 14, 0, "情人节"),
+            new DateInfoStruct(3, 1, 0, "国际海豹日"),
+            new DateInfoStruct(3, 5, 0, "学雷锋纪念日"),
+            new DateInfoStruct(3, 8, 0, "妇女节"),
+            new DateInfoStruct(3, 12, 0, "植树节 孙中山逝世纪念日"),
+            new DateInfoStruct(3, 14, 0, "国际警察日"),
+            new DateInfoStruct(3, 15, 0, "消费者权益日"),
+            new DateInfoStruct(3, 17, 0, "中国国医节 国际航海日"),
+            new DateInfoStruct(3, 21, 0, "世界森林日 消除种族歧视国际日 世界儿歌日"),
+            new DateInfoStruct(3, 22, 0, "世界水日"),
+            new DateInfoStruct(3, 24, 0, "世界防治结核病日"),
+            new DateInfoStruct(4, 1, 0, "愚人节"),
+            new DateInfoStruct(4, 5, 1, "清明节"),
+            new DateInfoStruct(4, 7, 0, "世界卫生日"),
+            new DateInfoStruct(4, 22, 0, "世界地球日"),
+            new DateInfoStruct(5, 1, 1, "劳动节"),
+            new DateInfoStruct(5, 4, 0, "青年节"),
+            new DateInfoStruct(5, 8, 0, "世界红十字日"),
+            new DateInfoStruct(5, 12, 0, "国际护士节"),
+            new DateInfoStruct(5, 31, 0, "世界无烟日"),
+            new DateInfoStruct(6, 1, 0, "国际儿童节"),
+            new DateInfoStruct(6, 5, 0, "世界环境保护日"),
+            new DateInfoStruct(6, 26, 0, "国际禁毒日"),
+            new DateInfoStruct(7, 1, 0, "建党节 香港回归纪念 世界建筑日"),
+            new DateInfoStruct(7, 11, 0, "世界人口日"),
+            new DateInfoStruct(8, 1, 0, "建军节"),
+            new DateInfoStruct(8, 8, 0, "中国男子节 父亲节"),
+            new DateInfoStruct(8, 15, 0, "抗日战争胜利纪念"),
+            new DateInfoStruct(9, 9, 0, "  逝世纪念"),
+            new DateInfoStruct(9, 10, 0, "教师节"),
+            new DateInfoStruct(9, 18, 0, "九·一八事变纪念日"),
+            new DateInfoStruct(9, 20, 0, "国际爱牙日"),
+            new DateInfoStruct(9, 27, 0, "世界旅游日"),
+            new DateInfoStruct(9, 28, 0, "孔子诞辰"),
+            new DateInfoStruct(10, 1, 7, "国庆节 国际音乐日"),
+            new DateInfoStruct(10, 24, 0, "联合国日"),
+            new DateInfoStruct(11, 10, 0, "世界青年节"),
+            new DateInfoStruct(11, 12, 0, "孙中山诞辰纪念"),
+            new DateInfoStruct(12, 1, 0, "世界艾滋病日"),
+            new DateInfoStruct(12, 3, 0, "世界残疾人日"),
+            new DateInfoStruct(12, 20, 0, "澳门回归纪念"),
+            new DateInfoStruct(12, 24, 0, "平安夜"),
+            new DateInfoStruct(12, 25, 0, "圣诞节"),
+            new DateInfoStruct(12, 26, 0, " 诞辰纪念")
+        };
+
+        /// <summary>
+        /// 按农历计算的节日
+        /// </summary>
+        public static HashSet<DateInfoStruct> LunarHolidayInfo { get; } = new HashSet<DateInfoStruct>
+        {
+            new DateInfoStruct(1, 1, 6, "春节"),
+            new DateInfoStruct(1, 15, 0, "元宵节"),
+            new DateInfoStruct(5, 5, 1, "端午节"),
+            new DateInfoStruct(7, 7, 0, "七夕情人节"),
+            new DateInfoStruct(7, 15, 0, "中元节 盂兰盆节"),
+            new DateInfoStruct(8, 15, 1, "中秋节"),
+            new DateInfoStruct(9, 9, 0, "重阳节"),
+            new DateInfoStruct(12, 8, 0, "腊八节"),
+            new DateInfoStruct(12, 23, 0, "北方小年(扫房)"),
+            new DateInfoStruct(12, 24, 0, "南方小年(掸尘)"),
+            //new HolidayStruct(12, 30, 0, "除夕")  //注意除夕需要其它方法进行计算
+        };
+
+        /// <summary>
+        /// 按农历计算的节日
+        /// </summary>
+        public static HashSet<DateTime> WorkDays { get; } = new HashSet<DateTime>();
+
+        private static readonly WeekHolidayStruct[] WHolidayInfo =
+        {
+            new WeekHolidayStruct(5, 2, 1, "母亲节"),
+            new WeekHolidayStruct(5, 3, 1, "全国助残日"),
+            new WeekHolidayStruct(6, 3, 1, "父亲节"),
+            new WeekHolidayStruct(9, 3, 3, "国际和平日"),
+            new WeekHolidayStruct(9, 4, 1, "国际聋人节"),
+            new WeekHolidayStruct(10, 1, 2, "国际住房日"),
+            new WeekHolidayStruct(10, 1, 4, "国际减轻自然灾害日"),
+            new WeekHolidayStruct(11, 4, 5, "感恩节")
+        };
+        #endregion
+
+        #endregion
+
+        /// <summary>
+        /// 用一个标准的公历日期来初使化
+        /// </summary>
+        /// <param name="dt"></param>
+        public ChineseCalendar(DateTime dt)
+        {
+            int i;
+            CheckDateLimit(dt);
+            _date = dt.Date;
+            _datetime = dt;
+            //农历日期计算部分
+            var temp = 0;
+            TimeSpan ts = _date - MinDay; //计算两天的基本差距
+            var offset = ts.Days;
+            for (i = MinYear; i <= MaxYear; i++)
+            {
+                temp = GetChineseYearDays(i); //求当年农历年天数
+                if (offset - temp < 1)
+                {
+                    break;
+                }
+
+                offset = offset - temp;
+            }
+
+            _cYear = i;
+            var leap = GetChineseLeapMonth(_cYear);
+            //设定当年是否有闰月
+            _cIsLeapYear = leap > 0;
+            _cIsLeapMonth = false;
+            for (i = 1; i <= 12; i++)
             {
-                if (leapMonth == lmonth)
+                //闰月
+                if (leap > 0 && i == leap + 1 && _cIsLeapMonth == false)
                 {
-                    //闰月
-                    isleap = true;
-                    lmonth--;
+                    _cIsLeapMonth = true;
+                    i = i - 1;
+                    temp = GetChineseLeapMonthDays(_cYear); //计算闰月天数
                 }
-                else if (lmonth > leapMonth)
+                else
                 {
-                    lmonth--;
+                    _cIsLeapMonth = false;
+                    temp = GetChineseMonthDays(_cYear, i); //计算非闰月天数
+                }
+
+                offset = offset - temp;
+                if (offset <= 0)
+                {
+                    break;
                 }
             }
-            return string.Concat(GetLunisolarYear(lyear), "年", isleap ? "闰" : string.Empty, GetLunisolarMonth(lmonth), "月", GetLunisolarDay(lday));
+
+            offset = offset + temp;
+            _cMonth = i;
+            _cDay = offset;
         }
 
         /// <summary>
-        /// 返回农历日期
+        /// 用农历的日期来初使化
         /// </summary>
-        public static string Now => DateTime.Now.GetChineseDateTimeNow();
+        /// <param name="cy">农历年</param>
+        /// <param name="cm">农历月</param>
+        /// <param name="cd">农历日</param>
+        /// <param name="leapMonthFlag">闰月标志</param>
+        public ChineseCalendar(int cy, int cm, int cd, bool leapMonthFlag)
+        {
+            int i, temp;
+            CheckChineseDateLimit(cy, cm, cd, leapMonthFlag);
+            _cYear = cy;
+            _cMonth = cm;
+            _cDay = cd;
+            var offset = 0;
+            for (i = MinYear; i < cy; i++)
+            {
+                temp = GetChineseYearDays(i); //求当年农历年天数
+                offset = offset + temp;
+            }
+
+            var leap = GetChineseLeapMonth(cy);
+            _cIsLeapYear = leap != 0;
+            _cIsLeapMonth = cm == leap && leapMonthFlag;
+            if (_cIsLeapYear == false || cm < leap) //当年没有闰月||计算月份小于闰月     
+            {
+                for (i = 1; i < cm; i++)
+                {
+                    temp = GetChineseMonthDays(cy, i); //计算非闰月天数
+                    offset = offset + temp;
+                }
+
+                //检查日期是否大于最大天
+                if (cd > GetChineseMonthDays(cy, cm))
+                {
+                    throw new ChineseCalendarException("不合法的农历日期");
+                }
+
+                offset = offset + cd; //加上当月的天数
+            }
+            else //是闰年,且计算月份大于或等于闰月
+            {
+                for (i = 1; i < cm; i++)
+                {
+                    temp = GetChineseMonthDays(cy, i); //计算非闰月天数
+                    offset = offset + temp;
+                }
+
+                if (cm > leap) //计算月大于闰月
+                {
+                    temp = GetChineseLeapMonthDays(cy); //计算闰月天数
+                    offset = offset + temp; //加上闰月天数
+                    if (cd > GetChineseMonthDays(cy, cm))
+                    {
+                        throw new ChineseCalendarException("不合法的农历日期");
+                    }
+
+                    offset = offset + cd;
+                }
+                else //计算月等于闰月
+                {
+                    //如果需要计算的是闰月,则应首先加上与闰月对应的普通月的天数
+                    if (_cIsLeapMonth) //计算月为闰月
+                    {
+                        temp = GetChineseMonthDays(cy, cm); //计算非闰月天数
+                        offset = offset + temp;
+                    }
+
+                    if (cd > GetChineseLeapMonthDays(cy))
+                    {
+                        throw new ChineseCalendarException("不合法的农历日期");
+                    }
+
+                    offset = offset + cd;
+                }
+            }
+
+            _date = MinDay.AddDays(offset);
+        }
+
+        #region 私有函数
 
         /// <summary>
-        /// 最大支持日期
+        /// 传回农历 y年m月的总天数
         /// </summary>
-        public static DateTime MaxSupportedDateTime => cCalendar.MaxSupportedDateTime;
+        /// <param name="year"></param>
+        /// <param name="month"></param>
+        /// <returns></returns>
+        private int GetChineseMonthDays(int year, int month)
+        {
+            if (BitTest32((LunarDateArray[year - MinYear] & 0x0000FFFF), (16 - month)))
+            {
+                return 30;
+            }
+
+            return 29;
+        }
 
         /// <summary>
-        /// 最小支持日期
+        /// 传回农历 y年闰哪个月 1-12 , 没闰传回 0
         /// </summary>
-        public static DateTime MinSupportedDateTime { get; } = cCalendar.MinSupportedDateTime;
+        /// <param name="year"></param>
+        /// <returns></returns>
+        private int GetChineseLeapMonth(int year)
+        {
+            return LunarDateArray[year - MinYear] & 0xF;
+        }
 
         /// <summary>
-        /// 返回生肖
+        /// 传回农历 y年闰月的天数
         /// </summary>
-        /// <param name="datetime">公历日期</param>
-        /// <returns>生肖</returns>
-        public static string GetShengXiao(this DateTime datetime) => shengxiao[cCalendar.GetTerrestrialBranch(cCalendar.GetSexagenaryYear(datetime)) - 1];
+        /// <param name="year"></param>
+        /// <returns></returns>
+        private int GetChineseLeapMonthDays(int year)
+        {
+            if (GetChineseLeapMonth(year) != 0)
+            {
+                return (LunarDateArray[year - MinYear] & 0x10000) != 0 ? 30 : 29;
+            }
 
-        #region 农历年
+            return 0;
+        }
 
         /// <summary>
-        /// 十天干
+        /// 取农历年一年的天数
         /// </summary>
-        private static string[] tiangan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
+        /// <param name="year"></param>
+        /// <returns></returns>
+        private int GetChineseYearDays(int year)
+        {
+            var sumDay = 348;
+            var i = 0x8000;
+            var info = LunarDateArray[year - MinYear] & 0x0FFFF;
+            //计算12个月中有多少天为30天
+            for (int m = 0; m < 12; m++)
+            {
+                var f = info & i;
+                if (f != 0)
+                {
+                    sumDay++;
+                }
+
+                i = i >> 1;
+            }
+
+            return sumDay + GetChineseLeapMonthDays(year);
+        }
+
+        /// <summary>
+        /// 获得当前时间的时辰
+        /// </summary>
+        /// <param name="dt"></param>
+        /// <returns></returns>
+        /// 
+        private string GetChineseHour(DateTime dt)
+        {
+            //计算时辰的地支
+            var hour = dt.Hour;
+            var minute = dt.Minute;
+            if (minute != 0) hour += 1;
+            var offset = hour / 2;
+            if (offset >= 12) offset = 0;
+            //计算天干
+            TimeSpan ts = _date - GanZhiStartDay;
+            var i = ts.Days % 60;
+            var indexGan = ((i % 10 + 1) * 2 - 1) % 10 - 1;
+            var tmpGan = GanStr.Substring(indexGan) + GanStr.Substring(0, indexGan + 2);
+            return tmpGan[offset].ToString() + ZhiStr[offset];
+        }
+
+        /// <summary>
+        /// 检查公历日期是否符合要求
+        /// </summary>
+        /// <param name="dt"></param>
+        private void CheckDateLimit(DateTime dt)
+        {
+            if ((dt < MinDay) || (dt > MaxDay))
+            {
+                throw new ChineseCalendarException("超出可转换的日期");
+            }
+        }
+
+        /// <summary>
+        /// 检查农历日期是否合理
+        /// </summary>
+        /// <param name="year"></param>
+        /// <param name="month"></param>
+        /// <param name="day"></param>
+        /// <param name="leapMonth"></param>
+        private void CheckChineseDateLimit(int year, int month, int day, bool leapMonth)
+        {
+            if ((year < MinYear) || (year > MaxYear))
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+
+            if ((month < 1) || (month > 12))
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+
+            if ((day < 1) || (day > 30)) //中国的月最多30天
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+
+            int leap = GetChineseLeapMonth(year); // 计算该年应该闰哪个月
+            if (leapMonth && month != leap)
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+        }
 
         /// <summary>
-        /// 十二地支
+        /// 将0-9转成汉字形式
         /// </summary>
-        private static string[] dizhi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
+        /// <param name="n"></param>
+        /// <returns></returns>
+        private string ConvertNumToChineseNum(char n)
+        {
+            if ((n < '0') || (n > '9')) return "";
+            switch (n)
+            {
+                case '0':
+                    return HzNum[0].ToString();
+                case '1':
+                    return HzNum[1].ToString();
+                case '2':
+                    return HzNum[2].ToString();
+                case '3':
+                    return HzNum[3].ToString();
+                case '4':
+                    return HzNum[4].ToString();
+                case '5':
+                    return HzNum[5].ToString();
+                case '6':
+                    return HzNum[6].ToString();
+                case '7':
+                    return HzNum[7].ToString();
+                case '8':
+                    return HzNum[8].ToString();
+                case '9':
+                    return HzNum[9].ToString();
+                default:
+                    return "";
+            }
+        }
+
+        /// <summary>
+        /// 测试某位是否为真
+        /// </summary>
+        /// <param name="num"></param>
+        /// <param name="bitpostion"></param>
+        /// <returns></returns>
+        private bool BitTest32(int num, int bitpostion)
+        {
+            if ((bitpostion > 31) || (bitpostion < 0))
+                throw new Exception("Error Param: bitpostion[0-31]:" + bitpostion.ToString());
+            int bit = 1 << bitpostion;
+            if ((num & bit) == 0)
+            {
+                return false;
+            }
+            else
+            {
+                return true;
+            }
+        }
 
         /// <summary>
-        /// 十二生肖
+        /// 将星期几转成数字表示
         /// </summary>
-        private static string[] shengxiao = { "鼠", "牛", "虎", "免", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
+        /// <param name="dayOfWeek"></param>
+        /// <returns></returns>
+        private int ConvertDayOfWeek(DayOfWeek dayOfWeek)
+        {
+            switch (dayOfWeek)
+            {
+                case DayOfWeek.Sunday:
+                    return 1;
+                case DayOfWeek.Monday:
+                    return 2;
+                case DayOfWeek.Tuesday:
+                    return 3;
+                case DayOfWeek.Wednesday:
+                    return 4;
+                case DayOfWeek.Thursday:
+                    return 5;
+                case DayOfWeek.Friday:
+                    return 6;
+                case DayOfWeek.Saturday:
+                    return 7;
+                default:
+                    return 0;
+            }
+        }
 
         /// <summary>
-        /// 返回农历天干地支年
+        /// 比较当天是不是指定的第周几
         /// </summary>
-        /// <param name="year">农历年</param>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
-        /// <returns>天干地支年</returns>
-        public static string GetLunisolarYear(int year)
+        /// <param name="date"></param>
+        /// <param name="month"></param>
+        /// <param name="week"></param>
+        /// <param name="day"></param>
+        /// <returns></returns>
+        private bool CompareWeekDayHoliday(DateTime date, int month, int week, int day)
         {
-            if (year > 3)
+            bool ret = false;
+            if (date.Month == month) //月份相同
             {
-                int tgIndex = (year - 4) % 10;
-                int dzIndex = (year - 4) % 12;
-                return string.Concat(tiangan[tgIndex], dizhi[dzIndex], "[", shengxiao[dzIndex], "]");
+                if (ConvertDayOfWeek(date.DayOfWeek) == day) //星期几相同
+                {
+                    DateTime firstDay = new DateTime(date.Year, date.Month, 1); //生成当月第一天
+                    int i = ConvertDayOfWeek(firstDay.DayOfWeek);
+                    int firWeekDays = 7 - ConvertDayOfWeek(firstDay.DayOfWeek) + 1; //计算第一周剩余天数
+                    if (i > day)
+                    {
+                        if ((week - 1) * 7 + day + firWeekDays == date.Day)
+                        {
+                            ret = true;
+                        }
+                    }
+                    else
+                    {
+                        if (day + firWeekDays + (week - 2) * 7 == date.Day)
+                        {
+                            ret = true;
+                        }
+                    }
+                }
             }
-            throw new ArgumentOutOfRangeException("无效的年份!");
+
+            return ret;
         }
 
         #endregion
 
-        #region 农历月
+        #region 节日
 
         /// <summary>
-        /// 农历月
+        /// 计算中国农历节日
         /// </summary>
-        private static string[] months = { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二(腊)" };
+        public string ChineseCalendarHoliday
+        {
+            get
+            {
+                string tempStr = "";
+                if (_cIsLeapMonth)
+                {
+                    return tempStr;
+                }
+
+                foreach (DateInfoStruct lh in LunarHolidayInfo)
+                {
+                    if (lh.Month == _cMonth && (_cDay >= lh.Day || _cDay <= lh.Day + lh.Recess))
+                    {
+                        tempStr = lh.HolidayName;
+                        break;
+                    }
+                }
+
+                //对除夕进行特别处理
+                if (_cMonth != 12)
+                {
+                    return tempStr;
+                }
+
+                int i = GetChineseMonthDays(_cYear, 12); //计算当年农历12月的总天数
+                if (_cDay == i) //如果为最后一天
+                {
+                    tempStr = "除夕";
+                }
+
+                return tempStr;
+            }
+        }
+
+        /// <summary>
+        /// 按某月第几周第几日计算的节日
+        /// </summary>
+        public string WeekDayHoliday
+        {
+            get
+            {
+                string tempStr = "";
+                foreach (WeekHolidayStruct wh in WHolidayInfo)
+                {
+                    if (!CompareWeekDayHoliday(_date, wh.Month, wh.WeekAtMonth, wh.WeekDay))
+                    {
+                        continue;
+                    }
+
+                    tempStr = wh.HolidayName;
+                    break;
+                }
+
+                return tempStr;
+            }
+        }
 
         /// <summary>
-        /// 返回农历月
+        /// 按公历日计算的节日
         /// </summary>
-        /// <param name="month">月份</param>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
-        /// <returns>农历月</returns>
-        public static string GetLunisolarMonth(int month)
+        public string DateHoliday
         {
-            if (month < 13 && month > 0)
+            get
             {
-                return months[month - 1];
+                string tempStr = "";
+                foreach (DateInfoStruct sh in SolarHolidayInfo)
+                {
+                    if ((sh.Month == _date.Month) && (_date.Day >= sh.Day || _date.Day <= sh.Day + sh.Recess))
+                    {
+                        tempStr = sh.HolidayName;
+                        break;
+                    }
+                }
+
+                return tempStr;
             }
-            throw new ArgumentOutOfRangeException("无效的月份!");
         }
 
+        public bool IsHoliday => !IsWorkDay;
+        public bool IsWorkDay => string.IsNullOrEmpty(DateHoliday) && string.IsNullOrEmpty(ChineseCalendarHoliday) && !IsWeekend() || WorkDays.Any(s => s.Date == _date);
+
+        /// <summary>
+        /// 是否是周末
+        /// </summary>
+        /// <returns></returns>
+        private bool IsWeekend()
+        {
+            return (_date.DayOfWeek == DayOfWeek.Saturday || _date.DayOfWeek == DayOfWeek.Sunday);
+        }
         #endregion
 
-        #region 农历日
-        private static string[] days1 = { "初", "十", "廿", "三" };
+        #region 公历日期
+
+        /// <summary>
+        /// 取对应的公历日期
+        /// </summary>
+        public DateTime Date
+        {
+            get => _date;
+            set => _date = value;
+        }
 
         /// <summary>
-        /// 日
+        /// 取星期几
         /// </summary>
-        private static string[] days = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
+        public DayOfWeek WeekDay => _date.DayOfWeek;
 
         /// <summary>
-        /// 返回农历日
+        /// 周几的字符
         /// </summary>
-        /// <param name="day">阳历日</param>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
-        /// <returns>农历日</returns>
-        public static string GetLunisolarDay(int day)
+        public string WeekDayStr
         {
-            if (day > 0 && day < 32)
+            get
             {
-                if (day != 20 && day != 30)
+                switch (_date.DayOfWeek)
                 {
-                    return string.Concat(days1[(day - 1) / 10], days[(day - 1) % 10]);
+                    case DayOfWeek.Sunday:
+                        return "星期日";
+                    case DayOfWeek.Monday:
+                        return "星期一";
+                    case DayOfWeek.Tuesday:
+                        return "星期二";
+                    case DayOfWeek.Wednesday:
+                        return "星期三";
+                    case DayOfWeek.Thursday:
+                        return "星期四";
+                    case DayOfWeek.Friday:
+                        return "星期五";
+                    default:
+                        return "星期六";
                 }
-                return string.Concat(days[(day - 1) / 10], days1[1]);
             }
-            throw new ArgumentOutOfRangeException("无效的日!");
         }
 
+        /// <summary>
+        /// 公历日期中文表示法 如一九九七年七月一日
+        /// </summary>
+        public string DateString => "公元" + _date.ToLongDateString();
+
+        /// <summary>
+        /// 当前是否公历闰年
+        /// </summary>
+        public bool IsLeapYear => DateTime.IsLeapYear(_date.Year);
+
+        /// <summary>
+        /// 28星宿计算
+        /// </summary>
+        public string ChineseConstellation
+        {
+            get
+            {
+                TimeSpan ts = _date - ChineseConstellationReferDay;
+                var offset = ts.Days;
+                var modStarDay = offset % 28;
+                return (modStarDay >= 0 ? ChineseConstellationName[modStarDay] : ChineseConstellationName[27 + modStarDay]);
+            }
+        }
+
+        /// <summary>
+        /// 时辰
+        /// </summary>
+        public string ChineseHour => GetChineseHour(_datetime);
+
+        #endregion
+
+        #region 农历日期
+
+        /// <summary>
+        /// 农历今天
+        /// </summary>
+        public static ChineseCalendar Today => new ChineseCalendar(DateTime.Today);
+
+        /// <summary>
+        /// 是否闰月
+        /// </summary>
+        public bool IsChineseLeapMonth => _cIsLeapMonth;
+
+        /// <summary>
+        /// 当年是否有闰月
+        /// </summary>
+        public bool IsChineseLeapYear => _cIsLeapYear;
+
+        /// <summary>
+        /// 农历日
+        /// </summary>
+        public int ChineseDay => _cDay;
+
+        /// <summary>
+        /// 农历日中文表示
+        /// </summary>
+        public string ChineseDayString
+        {
+            get
+            {
+                switch (_cDay)
+                {
+                    case 0:
+                        return "";
+                    case 10:
+                        return "初十";
+                    case 20:
+                        return "二十";
+                    case 30:
+                        return "三十";
+                    default:
+                        return NStr2[_cDay / 10] + NStr1[_cDay % 10].ToString();
+                }
+            }
+        }
+
+        /// <summary>
+        /// 农历的月份
+        /// </summary>
+        public int ChineseMonth => _cMonth;
+
+        /// <summary>
+        /// 农历月份字符串
+        /// </summary>
+        public string ChineseMonthString => MonthString[_cMonth];
+
+        /// <summary>
+        /// 取农历年份
+        /// </summary>
+        public int ChineseYear => _cYear;
+
+        /// <summary>
+        /// 取农历年字符串如,一九九七年
+        /// </summary>
+        public string ChineseYearString
+        {
+            get
+            {
+                string tempStr = "";
+                string num = _cYear.ToString();
+                for (int i = 0; i < 4; i++)
+                {
+                    tempStr += ConvertNumToChineseNum(num[i]);
+                }
+
+                return tempStr + "年";
+            }
+        }
+
+        /// <summary>
+        /// 取农历日期表示法:农历一九九七年正月初五
+        /// </summary>
+        public string ChineseDateString
+        {
+            get
+            {
+                if (_cIsLeapMonth)
+                {
+                    return "农历" + ChineseYearString + "闰" + ChineseMonthString + ChineseDayString;
+                }
+
+                return "农历" + ChineseYearString + ChineseMonthString + ChineseDayString;
+            }
+        }
+
+        /// <summary>
+        /// 定气法计算二十四节气,二十四节气是按地球公转来计算的,并非是阴历计算的
+        /// </summary>
+        /// <remarks>
+        /// 节气的定法有两种。古代历法采用的称为"恒气",即按时间把一年等分为24份,
+        /// 每一节气平均得15天有余,所以又称"平气"。现代农历采用的称为"定气",即
+        /// 按地球在轨道上的位置为标准,一周360°,两节气之间相隔15°。由于冬至时地
+        /// 球位于近日点附近,运动速度较快,因而太阳在黄道上移动15°的时间不到15天。
+        /// 夏至前后的情况正好相反,太阳在黄道上移动较慢,一个节气达16天之多。采用
+        /// 定气时可以保证春、秋两分必然在昼夜平分的那两天。
+        /// </remarks>
+        public string ChineseTwentyFourDay
+        {
+            get
+            {
+                DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
+                string tempStr = "";
+                var y = _date.Year;
+                for (int i = 1; i <= 24; i++)
+                {
+                    var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
+                    var newDate = baseDateAndTime.AddMinutes(num);
+                    if (newDate.DayOfYear != _date.DayOfYear)
+                    {
+                        continue;
+                    }
+
+                    tempStr = SolarTerm[i - 1];
+                    break;
+                }
+
+                return tempStr;
+            }
+        }
+
+        //当前日期前一个最近节气
+        public string ChineseTwentyFourPrevDay
+        {
+            get
+            {
+                DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
+                string tempStr = "";
+                var y = _date.Year;
+                for (int i = 24; i >= 1; i--)
+                {
+                    var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
+                    var newDate = baseDateAndTime.AddMinutes(num);
+                    if (newDate.DayOfYear < _date.DayOfYear)
+                    {
+                        tempStr = $"{SolarTerm[i - 1]}[{newDate:yyyy-MM-dd}]";
+                        break;
+                    }
+                }
+
+                return tempStr;
+            }
+        }
+
+        //当前日期后一个最近节气
+        public string ChineseTwentyFourNextDay
+        {
+            get
+            {
+                DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
+                string tempStr = "";
+                var y = _date.Year;
+                for (int i = 1; i <= 24; i++)
+                {
+                    var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
+                    var newDate = baseDateAndTime.AddMinutes(num);
+                    if (newDate.DayOfYear > _date.DayOfYear)
+                    {
+                        tempStr = $"{SolarTerm[i - 1]}[{newDate:yyyy-MM-dd}]";
+                        break;
+                    }
+                }
+
+                return tempStr;
+            }
+        }
+
+        #endregion
+
+        #region 星座
+
+        /// <summary>
+        /// 计算指定日期的星座序号 
+        /// </summary>
+        /// <returns></returns>
+        public string Constellation
+        {
+            get
+            {
+                int index;
+                var m = _date.Month;
+                var d = _date.Day;
+                var y = m * 100 + d;
+                if (((y >= 321) && (y <= 419)))
+                {
+                    index = 0;
+                }
+                else if ((y >= 420) && (y <= 520))
+                {
+                    index = 1;
+                }
+                else if ((y >= 521) && (y <= 620))
+                {
+                    index = 2;
+                }
+                else if ((y >= 621) && (y <= 722))
+                {
+                    index = 3;
+                }
+                else if ((y >= 723) && (y <= 822))
+                {
+                    index = 4;
+                }
+                else if ((y >= 823) && (y <= 922))
+                {
+                    index = 5;
+                }
+                else if ((y >= 923) && (y <= 1022))
+                {
+                    index = 6;
+                }
+                else if ((y >= 1023) && (y <= 1121))
+                {
+                    index = 7;
+                }
+                else if ((y >= 1122) && (y <= 1221))
+                {
+                    index = 8;
+                }
+                else if ((y >= 1222) || (y <= 119))
+                {
+                    index = 9;
+                }
+                else if ((y >= 120) && (y <= 218))
+                {
+                    index = 10;
+                }
+                else if ((y >= 219) && (y <= 320))
+                {
+                    index = 11;
+                }
+                else
+                {
+                    index = 0;
+                }
+
+                return ConstellationName[index];
+            }
+        }
+
+        #endregion
+
+        #region 属相
+
+        /// <summary>
+        /// 计算属相的索引,注意虽然属相是以农历年来区别的,但是目前在实际使用中是按公历来计算的
+        /// 鼠年为1,其它类推
+        /// </summary>
+        public int Animal
+        {
+            get
+            {
+                int offset = _date.Year - AnimalStartYear;
+                return (offset % 12) + 1;
+            }
+        }
+
+        /// <summary>
+        /// 取属相字符串
+        /// </summary>
+        public string AnimalString
+        {
+            get
+            {
+                int offset = _date.Year - AnimalStartYear; //阳历计算
+                return AnimalStr[offset % 12].ToString();
+            }
+        }
+
+        #endregion
+
+        #region 天干地支
+
+        /// <summary>
+        /// 取农历年的干支表示法如 乙丑年
+        /// </summary>
+        public string GanZhiYearString
+        {
+            get
+            {
+                int i = (_cYear - GanZhiStartYear) % 60; //计算干支
+                var tempStr = GanStr[i % 10] + ZhiStr[i % 12].ToString() + "年";
+                return tempStr;
+            }
+        }
+
+        /// <summary>
+        /// 取干支的月表示字符串,注意农历的闰月不记干支
+        /// </summary>
+        public string GanZhiMonthString
+        {
+            get
+            {
+                //每个月的地支总是固定的,而且总是从寅月开始
+                int zhiIndex;
+                if (_cMonth > 10)
+                {
+                    zhiIndex = _cMonth - 10;
+                }
+                else
+                {
+                    zhiIndex = _cMonth + 2;
+                }
+
+                var zhi = ZhiStr[zhiIndex - 1].ToString();
+                //根据当年的干支年的干来计算月干的第一个
+                int ganIndex = 1;
+                int i = (_cYear - GanZhiStartYear) % 60; //计算干支
+                switch (i % 10)
+                {
+                    case 0: //甲
+                        ganIndex = 3;
+                        break;
+                    case 1: //乙
+                        ganIndex = 5;
+                        break;
+                    case 2: //丙
+                        ganIndex = 7;
+                        break;
+                    case 3: //丁
+                        ganIndex = 9;
+                        break;
+                    case 4: //戊
+                        ganIndex = 1;
+                        break;
+                    case 5: //己
+                        ganIndex = 3;
+                        break;
+                    case 6: //庚
+                        ganIndex = 5;
+                        break;
+                    case 7: //辛
+                        ganIndex = 7;
+                        break;
+                    case 8: //壬
+                        ganIndex = 9;
+                        break;
+                    case 9: //癸
+                        ganIndex = 1;
+                        break;
+                }
+
+                var gan = GanStr[(ganIndex + _cMonth - 2) % 10].ToString();
+                return gan + zhi + "月";
+            }
+        }
+
+        /// <summary>
+        /// 取干支日表示法
+        /// </summary>
+        public string GanZhiDayString
+        {
+            get
+            {
+                TimeSpan ts = _date - GanZhiStartDay;
+                var offset = ts.Days;
+                var i = offset % 60;
+                return GanStr[i % 10].ToString() + ZhiStr[i % 12] + "日";
+            }
+        }
+
+        /// <summary>
+        /// 取当前日期的干支表示法如 甲子年乙丑月丙庚日
+        /// </summary>
+        public string GanZhiDateString => GanZhiYearString + GanZhiMonthString + GanZhiDayString;
+
         #endregion
+
+        /// <summary>
+        /// 取下一天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar NextDay()
+        {
+            DateTime nextDay = _date.AddDays(1);
+            return new ChineseCalendar(nextDay);
+        }
+
+        /// <summary>
+        /// 取前一天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar PervDay()
+        {
+            DateTime pervDay = _date.AddDays(-1);
+            return new ChineseCalendar(pervDay);
+        }
+
+        /// <summary>
+        /// 取下n天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar AddDays(int days)
+        {
+            DateTime nextDay = _date.AddDays(days);
+            return new ChineseCalendar(nextDay);
+        }
+
+        /// <summary>
+        /// 加n月
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar AddMonths(int months)
+        {
+            DateTime nextDay = _date.AddMonths(months);
+            return new ChineseCalendar(nextDay);
+        }
     }
-}
+}

+ 18 - 0
Masuit.Tools.Core/DateTimeExt/DateInfoStruct.cs

@@ -0,0 +1,18 @@
+namespace Masuit.Tools.DateTimeExt
+{
+    public struct DateInfoStruct
+    {
+        public readonly int Month;
+        public readonly int Day;
+        public readonly int Recess; //假期长度
+        public readonly string HolidayName;
+
+        public DateInfoStruct(int month, int day, int recess, string name)
+        {
+            Month = month;
+            Day = day;
+            Recess = recess;
+            HolidayName = name;
+        }
+    }
+}

+ 6 - 6
Masuit.Tools.Core/DateTimeExt/DateTimeHelper.cs

@@ -17,7 +17,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>该年周数</returns>
         public static int GetWeekAmount(this DateTime _, int year)
         {
-            var end = new System.DateTime(year, 12, 31); //该年最后一天
+            var end = new DateTime(year, 12, 31); //该年最后一天
             var gc = new GregorianCalendar();
             return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday); //该年星期数
         }
@@ -73,7 +73,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <param name="nNumWeek">第几周</param>
         /// <param name="dtWeekStart">开始日期</param>
         /// <param name="dtWeekeEnd">结束日期</param>
-        public static void GetWeekWorkTime(this DateTime _, int nYear, int nNumWeek, out System.DateTime dtWeekStart, out System.DateTime dtWeekeEnd)
+        public static void GetWeekWorkTime(this DateTime _, int nYear, int nNumWeek, out DateTime dtWeekStart, out DateTime dtWeekeEnd)
         {
             var dt = new DateTime(nYear, 1, 1);
             dt += new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
@@ -84,10 +84,10 @@ namespace Masuit.Tools.DateTimeExt
         #region P/Invoke 设置本地时间
 
         [DllImport("kernel32.dll")]
-        private static extern bool SetLocalTime(ref SYSTEMTIME time);
+        private static extern bool SetLocalTime(ref SystemTime time);
 
         [StructLayout(LayoutKind.Sequential)]
-        private struct SYSTEMTIME
+        private struct SystemTime
         {
             public short year;
             public short month;
@@ -105,7 +105,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <param name="dt">DateTime对象</param>
         public static void SetLocalTime(this DateTime dt)
         {
-            SYSTEMTIME st;
+            SystemTime st;
 
             st.year = (short)dt.Year;
             st.month = (short)dt.Month;
@@ -121,4 +121,4 @@ namespace Masuit.Tools.DateTimeExt
 
         #endregion
     }
-}
+}

+ 5 - 1
Masuit.Tools.Core/DateTimeExt/DateUtil.cs

@@ -1,6 +1,6 @@
 using System;
 
-namespace Masuit.Tools.Core.DateTimeExt
+namespace Masuit.Tools.DateTimeExt
 {
     /// <summary>
     /// 日期操作工具类
@@ -33,6 +33,7 @@ namespace Masuit.Tools.Core.DateTimeExt
             {
                 return fDateTime;
             }
+
             var s = Convert.ToDateTime(fDateTime);
             return s.ToString(formatStr);
         }
@@ -156,6 +157,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                     days = 31;
                     break;
             }
+
             return days;
         }
 
@@ -247,6 +249,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                     week = "星期日";
                     break;
             }
+
             return week;
         }
 
@@ -282,6 +285,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                     week = "7";
                     break;
             }
+
             return week;
         }
 

+ 25 - 43
Masuit.Tools.Core/DateTimeExt/TimeHelper.cs

@@ -1,7 +1,7 @@
 using System;
 using System.Globalization;
 
-namespace Masuit.Tools.Core.DateTimeExt
+namespace Masuit.Tools.DateTimeExt
 {
     /// <summary>
     /// 时间相关操作帮助类
@@ -29,8 +29,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                     break;
                 case 2:
                     firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
-                    if (DateTime.IsLeapYear(DateTime.Now.Year)) lastDay = DateTime.Now.ToString(year + "-0" + month + "-29");
-                    else lastDay = DateTime.Now.ToString(year + "-0" + month + "-28");
+                    lastDay = DateTime.IsLeapYear(DateTime.Now.Year) ? DateTime.Now.ToString(year + "-0" + month + "-29") : DateTime.Now.ToString(year + "-0" + month + "-28");
                     break;
                 case 3:
                     firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
@@ -87,12 +86,14 @@ namespace Masuit.Tools.Core.DateTimeExt
         /// <returns>xxxx年xx月xx日</returns>
         public static string GetFormatDate(this DateTime dt, char separator)
         {
-            if (dt != null && !dt.Equals(DBNull.Value))
+            if (dt.Equals(DBNull.Value))
             {
-                string tem = $"yyyy{separator}MM{separator}dd";
-                return dt.ToString(tem);
+                return GetFormatDate(DateTime.Now, separator);
             }
-            return GetFormatDate(DateTime.Now, separator);
+
+            string tem = $"yyyy{separator}MM{separator}dd";
+            return dt.ToString(tem);
+
         }
 
         #endregion
@@ -107,12 +108,14 @@ namespace Masuit.Tools.Core.DateTimeExt
         /// <returns> xx时xx分xx秒 </returns>
         public static string GetFormatTime(this DateTime dt, char separator)
         {
-            if (dt != null && !dt.Equals(DBNull.Value))
+            if (dt.Equals(DBNull.Value))
             {
-                string tem = string.Format("hh{0}mm{1}ss", separator, separator);
-                return dt.ToString(tem);
+                return GetFormatDate(DateTime.Now, separator);
             }
-            return GetFormatDate(DateTime.Now, separator);
+
+            string tem = $"hh{separator}mm{separator}ss";
+            return dt.ToString(tem);
+
         }
 
         #endregion
@@ -170,34 +173,6 @@ namespace Masuit.Tools.Core.DateTimeExt
 
         #endregion
 
-        #region 格式化日期时间
-
-        /// <summary>
-        /// 格式化日期时间
-        /// </summary>
-        /// <param name="dateTime1">日期时间</param>
-        /// <param name="dateMode">显示模式</param>
-        /// <returns>0-9种模式的日期</returns>
-        public static string FormatDate(this DateTime dateTime1, string dateMode)
-        {
-            switch (dateMode)
-            {
-                case "0": return dateTime1.ToString("yyyy-MM-dd");
-                case "1": return dateTime1.ToString("yyyy-MM-dd HH:mm:ss");
-                case "2": return dateTime1.ToString("yyyy/MM/dd");
-                case "3": return dateTime1.ToString("yyyy年MM月dd日");
-                case "4": return dateTime1.ToString("MM-dd");
-                case "5": return dateTime1.ToString("MM/dd");
-                case "6": return dateTime1.ToString("MM月dd日");
-                case "7": return dateTime1.ToString("yyyy-MM");
-                case "8": return dateTime1.ToString("yyyy/MM");
-                case "9": return dateTime1.ToString("yyyy年MM月");
-                default: return dateTime1.ToString(CultureInfo.CurrentCulture);
-            }
-        }
-
-        #endregion
-
         #region 得到随机日期
 
         /// <summary>
@@ -229,6 +204,7 @@ namespace Masuit.Tools.Core.DateTimeExt
             {
                 return time1;
             }
+
             int maxValue = iTotalSecontds;
             if (iTotalSecontds <= int.MinValue) maxValue = int.MinValue + 1;
             int i = random.Next(Math.Abs(maxValue));
@@ -320,6 +296,7 @@ namespace Masuit.Tools.Core.DateTimeExt
                 if (ts.Hours > 1) dateDiff = ts.Hours + "小时前";
                 else dateDiff = ts.Minutes + "分钟前";
             }
+
             return dateDiff;
         }
 
@@ -363,26 +340,31 @@ namespace Masuit.Tools.Core.DateTimeExt
                 strResout += iTatol / iYear + "年";
                 iTatol %= iYear; //剩余
             }
+
             if (iTatol > iMonth)
             {
                 strResout += iTatol / iMonth + "月";
                 iTatol %= iMonth;
             }
+
             if (iTatol > iDay)
             {
                 strResout += iTatol / iDay + "天";
                 iTatol %= iDay;
             }
+
             if (iTatol > iHours)
             {
                 strResout += iTatol / iHours + "小时";
                 iTatol %= iHours;
             }
+
             if (iTatol > iMinutes)
             {
                 strResout += iTatol / iMinutes + "分";
                 iTatol %= iMinutes;
             }
+
             strResout += iTatol + "秒";
             return strResout;
         }
@@ -394,12 +376,12 @@ namespace Masuit.Tools.Core.DateTimeExt
         /// <summary>
         /// C#的时间到Javascript的时间的转换
         /// </summary>
-        /// <param name="TheDate">C#的时间</param>
+        /// <param name="theDate">C#的时间</param>
         /// <returns>Javascript的时间</returns>
-        public static long CsharpTime2JavascriptTime(this DateTime TheDate)
+        public static long CsharpTime2JavascriptTime(this DateTime theDate)
         {
             DateTime d1 = new DateTime(1970, 1, 1);
-            DateTime d2 = TheDate.ToUniversalTime();
+            DateTime d2 = theDate.ToUniversalTime();
             TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
             return (long)ts.TotalMilliseconds;
         }
@@ -425,7 +407,7 @@ namespace Masuit.Tools.Core.DateTimeExt
         public static long CsharpTime2PhpTime(this DateTime time)
         {
             DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
-                                                           //注意这里有时区问题,用now就要减掉8个小时
+            //注意这里有时区问题,用now就要减掉8个小时
             return (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000;
         }
 

+ 18 - 0
Masuit.Tools.Core/DateTimeExt/WeekHolidayStruct.cs

@@ -0,0 +1,18 @@
+namespace Masuit.Tools.DateTimeExt
+{
+    public struct WeekHolidayStruct
+    {
+        public readonly int Month;
+        public readonly int WeekAtMonth;
+        public readonly int WeekDay;
+        public readonly string HolidayName;
+
+        public WeekHolidayStruct(int month, int weekAtMonth, int weekDay, string name)
+        {
+            Month = month;
+            WeekAtMonth = weekAtMonth;
+            WeekDay = weekDay;
+            HolidayName = name;
+        }
+    }
+}

+ 3 - 8
Masuit.Tools.Core/ExpressionGenericMapper.cs

@@ -2,7 +2,7 @@
 using System.Collections.Generic;
 using System.Linq.Expressions;
 
-namespace Masuit.Tools.Core
+namespace Masuit.Tools
 {
     /// <summary>
     /// 生成表达式目录树  泛型缓存
@@ -43,12 +43,7 @@ namespace Masuit.Tools.Core
                 func = lambda.Compile();
             }
 
-            if (source == null)
-            {
-                return default(TDestination);
-            }
-
-            return ((Func<TSource, TDestination>)func)(source); //拼装是一次性的
+            return source == null ? default(TDestination) : ((Func<TSource, TDestination>)func)(source);
         }
 
         /// <summary>
@@ -96,4 +91,4 @@ namespace Masuit.Tools.Core
             }
         }
     }
-}
+}

文件差異過大導致無法顯示
+ 179 - 399
Masuit.Tools.Core/Extensions.cs


+ 70 - 0
Masuit.Tools.Core/Files/ExtensionAttach.cs

@@ -0,0 +1,70 @@
+using Microsoft.Win32;
+using System;
+using System.IO;
+using System.Security;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// 文件关联
+    /// </summary>
+    public static class ExtensionAttach
+    {
+        /// <summary>
+        /// 关联文件
+        /// </summary>
+        /// <param name="filePathString">应用程序路径</param>
+        /// <param name="pFileTypeName">文件类型</param>
+        /// <exception cref="SecurityException">The user does not have the permissions required to access the registry key in the specified mode. </exception>
+        /// <exception cref="UnauthorizedAccessException">The user does not have the necessary registry rights.</exception>
+        /// <exception cref="IOException">The nesting level exceeds 510.-or-A system error occurred, such as deletion of the key, or an attempt to create a key in the <see cref="F:Microsoft.Win32.Registry.LocalMachine" /> root.</exception>
+        public static void SaveReg(string filePathString, string pFileTypeName)
+        {
+            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey("", true); //打开注册表
+            RegistryKey vrPkey = regKey?.OpenSubKey(pFileTypeName, true);
+            if (vrPkey != null)
+            {
+                regKey.DeleteSubKey(pFileTypeName, true);
+            }
+
+            regKey?.CreateSubKey(pFileTypeName);
+            vrPkey = regKey?.OpenSubKey(pFileTypeName, true);
+            vrPkey?.SetValue("", "Exec");
+            vrPkey = regKey?.OpenSubKey("Exec", true);
+            if (vrPkey != null) regKey.DeleteSubKeyTree("Exec"); //如果等于空就删除注册表DSKJIVR
+
+            regKey?.CreateSubKey("Exec");
+            vrPkey = regKey?.OpenSubKey("Exec", true);
+            vrPkey?.CreateSubKey("shell");
+            vrPkey = vrPkey?.OpenSubKey("shell", true); //写入必须路径
+            vrPkey?.CreateSubKey("open");
+            vrPkey = vrPkey?.OpenSubKey("open", true);
+            vrPkey?.CreateSubKey("command");
+            vrPkey = vrPkey?.OpenSubKey("command", true);
+            string pathString = "\"" + filePathString + "\" \"%1\"";
+            vrPkey?.SetValue("", pathString); //写入数据
+        }
+
+        /// <summary>
+        /// 取消文件关联
+        /// </summary>
+        /// <param name="pFileTypeName">文件类型</param>
+        /// <exception cref="SecurityException">The user does not have the permissions required to access the registry key in the specified mode. </exception>
+        /// <exception cref="UnauthorizedAccessException">The user does not have the necessary registry rights.</exception>
+        /// <exception cref="IOException">An I/O error has occurred.</exception>
+        public static void DelReg(string pFileTypeName)
+        {
+            RegistryKey regkey = Registry.ClassesRoot.OpenSubKey("", true);
+            RegistryKey vrPkey = regkey?.OpenSubKey(pFileTypeName);
+            if (vrPkey != null)
+            {
+                regkey.DeleteSubKey(pFileTypeName, true);
+            }
+
+            if (vrPkey != null)
+            {
+                regkey.DeleteSubKeyTree("Exec");
+            }
+        }
+    }
+}

+ 7 - 2
Masuit.Tools.Core/Files/FileExt.cs

@@ -39,7 +39,7 @@ namespace Masuit.Tools.Files
             using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
             {
                 byte[] buf = new byte[bufferSize];
-                int len = 0;
+                int len;
                 await Task.Run(() =>
                 {
                     using (fs)
@@ -118,6 +118,7 @@ namespace Masuit.Tools.Files
             {
                 throw new ArgumentNullException("algName 不能为 null");
             }
+
             if (string.Compare(algName, "sha1", true) == 0)
             {
                 algorithm = System.Security.Cryptography.SHA1.Create();
@@ -128,8 +129,10 @@ namespace Masuit.Tools.Files
                 {
                     throw new Exception("algName 只能使用 sha1 或 md5");
                 }
+
                 algorithm = System.Security.Cryptography.MD5.Create();
             }
+
             return algorithm.ComputeHash(stream);
         }
 
@@ -146,6 +149,7 @@ namespace Masuit.Tools.Files
             {
                 throw new ArgumentNullException("algName 不能为 null");
             }
+
             if (string.Compare(algName, "sha1", true) == 0)
             {
                 algorithm = System.Security.Cryptography.SHA1.Create();
@@ -156,10 +160,11 @@ namespace Masuit.Tools.Files
                 {
                     throw new Exception("algName 只能使用 sha1 或 md5");
                 }
+
                 algorithm = System.Security.Cryptography.MD5.Create();
             }
-            return await Task.Run(() => algorithm.ComputeHash(stream)).ConfigureAwait(false);
 
+            return await Task.Run(() => algorithm.ComputeHash(stream)).ConfigureAwait(false);
         }
 
         /// <summary>

+ 1 - 1
Masuit.Tools.Core/Files/INIFile.cs

@@ -86,4 +86,4 @@ namespace Masuit.Tools.Files
             IniWriteValue(Section, null, null);
         }
     }
-}
+}

+ 133 - 323
Masuit.Tools.Core/Html/HtmlHelper.cs

@@ -3,12 +3,12 @@ using System;
 using System.IO;
 using System.IO.Compression;
 using System.Net;
+using System.Net.Http;
 using System.Text;
 using System.Text.RegularExpressions;
-using System.Threading;
 using System.Web;
 
-namespace Masuit.Tools.Core.Html
+namespace Masuit.Tools.Html
 {
     /// <summary>
     ///1、获取HTML<br/>
@@ -41,28 +41,16 @@ namespace Masuit.Tools.Core.Html
     public static partial class HtmlTools
     {
         #region 私有字段
-        private static CookieContainer cc = new CookieContainer();
+
         private static string contentType = "application/x-www-form-urlencoded";
-        private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg," +
-                                       " application/x-shockwave-flash, application/x-silverlight, " +
-                                       "application/vnd.ms-excel, application/vnd.ms-powerpoint, " +
-                                       "application/msword, application/x-ms-application," +
-                                       " application/x-ms-xbap," +
-                                       " application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
-        private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;" +
-                                          " .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
+        private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg," + " application/x-shockwave-flash, application/x-silverlight, " + "application/vnd.ms-excel, application/vnd.ms-powerpoint, " + "application/msword, application/x-ms-application," + " application/x-ms-xbap," + " application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
+        private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;" + " .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
         private static int delay = 1000;
-        private static int currentTry = 0;
+        private static int currentTry;
+
         #endregion
 
         #region 公有属性
-        /// <summary> 
-        /// Cookie容器
-        /// </summary> 
-        public static CookieContainer CookieContainer
-        {
-            get { return cc; }
-        }
 
         /// <summary> 
         /// 获取网页源码时使用的编码
@@ -80,13 +68,17 @@ namespace Masuit.Tools.Core.Html
                 return r.Next(delay, delay * 2);
                 // return (r.Next(delay / 1000, delay / 1000 * 2)) * 1000;
             }
-            set { delay = value; }
+            set
+            {
+                delay = value;
+            }
         }
 
         /// <summary>
         /// 最大尝试次数
         /// </summary>
         public static int MaxTry { get; set; } = 300;
+
         #endregion
 
         #region 1、获取HTML
@@ -105,123 +97,34 @@ namespace Masuit.Tools.Core.Html
             {
                 return strText.Substring(0, length);
             }
+
             return strText;
         }
 
         /// <summary>
-        /// 获取指定页面的HTML代码
+        /// 获取HTML
         /// </summary>
         /// <param name="_"></param>
-        /// <param name="url">指定页面的路径</param>
-        /// <param name="postData">post 提交的字符串</param>
-        /// <param name="isPost">是否以post方式发送请求</param>
-        /// <param name="cookieContainer">Cookie集合</param>
-        public static string GetHtml(this HttpWebRequest _, string url, string postData, bool isPost, CookieContainer cookieContainer)
+        /// <param name="url">地址</param>
+        public static string GetHtml(this HttpClient _, string url)
         {
-            if (string.IsNullOrEmpty(postData))
+            return _.GetAsync(url).ContinueWith(task =>
             {
-                return GetHtml(null, url, cookieContainer);
-            }
-            Thread.Sleep(NetworkDelay);
-            currentTry++;
-            HttpWebRequest httpWebRequest = null;
-            HttpWebResponse httpWebResponse = null;
-            try
-            {
-                byte[] byteRequest = Encoding.Default.GetBytes(postData);
-
-                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
-                httpWebRequest.CookieContainer = cookieContainer;
-                httpWebRequest.ContentType = contentType;
-                httpWebRequest.ServicePoint.ConnectionLimit = MaxTry;
-                httpWebRequest.Referer = url;
-                httpWebRequest.Accept = accept;
-                httpWebRequest.UserAgent = userAgent;
-                httpWebRequest.Method = isPost ? "POST" : "GET";
-                httpWebRequest.ContentLength = byteRequest.Length;
-
-                httpWebRequest.AllowAutoRedirect = false;
-
-                Stream stream = httpWebRequest.GetRequestStream();
-                stream.Write(byteRequest, 0, byteRequest.Length);
-                stream.Close();
-
-                try
-                {
-                    httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-                    //redirectURL = httpWebResponse.Headers["Location"];// Get redirected uri
-                }
-                catch (WebException ex)
+                if (task.IsCanceled || task.IsFaulted)
                 {
-                    httpWebResponse = (HttpWebResponse)ex.Response;
+                    return string.Empty;
                 }
-                //httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-
-                Stream responseStream = httpWebResponse.GetResponseStream();
-                StreamReader streamReader = new StreamReader(responseStream, Encoding);
-                string html = streamReader.ReadToEnd();
-                streamReader.Close();
-                responseStream.Close();
-                currentTry = 0;
-                httpWebRequest.Abort();
-                httpWebResponse.Close();
-                return html;
-            }
-            catch (Exception)
-            {
-                if (currentTry <= MaxTry)
+
+                var resp = task.Result;
+                if (resp.IsSuccessStatusCode)
                 {
-                    GetHtml(null, url, postData, isPost, cookieContainer);
+                    return resp.Content.ReadAsStringAsync().Result;
                 }
-                currentTry--;
-                if (httpWebRequest != null) httpWebRequest.Abort();
-                if (httpWebResponse != null) httpWebResponse.Close();
-                return string.Empty;
-            }
-        }
 
-        /// <summary>
-        /// 获取HTML
-        /// </summary>
-        /// <param name="_"></param>
-        /// <param name="url">地址</param>
-        /// <param name="cookieContainer">Cookie集合</param>
-        public static string GetHtml(this HttpWebRequest _, string url, CookieContainer cookieContainer)
-        {
-            Thread.Sleep(NetworkDelay);
-            currentTry++;
-            HttpWebRequest httpWebRequest = null;
-            HttpWebResponse httpWebResponse = null;
-            try
-            {
-                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
-                httpWebRequest.CookieContainer = cookieContainer;
-                httpWebRequest.ContentType = contentType;
-                httpWebRequest.ServicePoint.ConnectionLimit = MaxTry;
-                httpWebRequest.Referer = url;
-                httpWebRequest.Accept = accept;
-                httpWebRequest.UserAgent = userAgent;
-                httpWebRequest.Method = "GET";
-                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-                Stream responseStream = httpWebResponse.GetResponseStream();
-                StreamReader streamReader = new StreamReader(responseStream, Encoding);
-                string html = streamReader.ReadToEnd();
-                streamReader.Close();
-                responseStream.Close();
-                currentTry--;
-                httpWebRequest.Abort();
-                httpWebResponse.Close();
-                return html;
-            }
-            catch (Exception)
-            {
-                if (currentTry <= MaxTry) GetHtml(null, url, cookieContainer);
-                currentTry--;
-                if (httpWebRequest != null) httpWebRequest.Abort();
-                if (httpWebResponse != null) httpWebResponse.Close();
                 return string.Empty;
-            }
+            }).Result;
         }
+
         #endregion
 
         #region 2、获取字符流
@@ -237,50 +140,25 @@ namespace Masuit.Tools.Core.Html
         /// ---------------------------------------------------------------------------------------------------------------
         /// <param name="_"></param>
         /// <param name="url">地址</param>
-        ///  <param name="cookieContainer">cookieContainer</param>
-        public static Stream GetStream(this HttpWebRequest _, string url, CookieContainer cookieContainer)
+        public static Stream GetStream(this HttpClient _, string url)
         {
-            currentTry++;
-
-            HttpWebRequest httpWebRequest = null;
-            HttpWebResponse httpWebResponse = null;
-
-            try
-            {
-                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
-                httpWebRequest.CookieContainer = cookieContainer;
-                httpWebRequest.ContentType = contentType;
-                httpWebRequest.ServicePoint.ConnectionLimit = MaxTry;
-                httpWebRequest.Referer = url;
-                httpWebRequest.Accept = accept;
-                httpWebRequest.UserAgent = userAgent;
-                httpWebRequest.Method = "GET";
-
-                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-                Stream responseStream = httpWebResponse.GetResponseStream();
-                currentTry--;
-                return responseStream;
-            }
-            catch (Exception)
+            return _.GetAsync(url).ContinueWith(task =>
             {
-                if (currentTry <= MaxTry)
+                if (task.IsCanceled || task.IsFaulted)
                 {
-                    GetHtml(null, url, cookieContainer);
+                    return null;
                 }
 
-                currentTry--;
-
-                if (httpWebRequest != null)
-                {
-                    httpWebRequest.Abort();
-                }
-                if (httpWebResponse != null)
+                var resp = task.Result;
+                if (resp.IsSuccessStatusCode)
                 {
-                    httpWebResponse.Close();
+                    return resp.Content.ReadAsStreamAsync().Result;
                 }
+
                 return null;
-            }
+            }).Result;
         }
+
         #endregion
 
         #region 3、清除HTML标记
@@ -293,9 +171,9 @@ namespace Masuit.Tools.Core.Html
         public static string ClearHtml(this string html)
         {
             string s = Regex.Match(Regex.Replace(html, @"background-color:#?\w{3,7}|font-family:'?[\w|\(|\)]*'?;?", string.Empty), @"<body[^>]*>([\s\S]*)<\/body>").Groups[1].Value.Replace("&#xa0;", string.Empty);
-            s = Regex.Replace(s, @"\w+-?\w+:0\w+;?", string.Empty);//去除多余的零值属性
-            s = Regex.Replace(s, "alt=\"(.+?)\"", string.Empty);//除去alt属性
-            s = Regex.Replace(s, @"-aw.+?\s", string.Empty);//去除Word产生的-aw属性
+            s = Regex.Replace(s, @"\w+-?\w+:0\w+;?", string.Empty); //去除多余的零值属性
+            s = Regex.Replace(s, "alt=\"(.+?)\"", string.Empty); //除去alt属性
+            s = Regex.Replace(s, @"-aw.+?\s", string.Empty); //去除Word产生的-aw属性
             return s;
         }
 
@@ -307,25 +185,24 @@ namespace Masuit.Tools.Core.Html
         public static string RemoveHtml(this string htmlstring)
         {
             //删除脚本   
-            htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
 
             //删除HTML   
             Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
             htmlstring = regex.Replace(htmlstring, "");
-            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "<(.[^>]*)>", "", RegexOptions.IgnoreCase);
             htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
-
-            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "-->", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "<!--.*", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(quot|#34);", "\"", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(amp|#38);", "&", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(lt|#60);", "<", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(gt|#62);", ">", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
             htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
 
             htmlstring.Replace("<", "");
@@ -338,7 +215,9 @@ namespace Masuit.Tools.Core.Html
         #endregion
 
         #region 4、匹配页面的链接
+
         #region 4.1获取页面的链接正则
+
         /// <summary>
         /// 4.1获取页面的链接正则
         /// </summary>
@@ -351,11 +230,14 @@ namespace Masuit.Tools.Core.Html
             {
                 MatchVale += (m.Value).ToLower().Replace("href=", "").Trim() + "|";
             }
+
             return MatchVale;
         }
+
         #endregion
 
         #region  4.2取得所有链接URL
+
         /// <summary>
         /// 4.2取得所有链接URL
         /// </summary>
@@ -370,11 +252,14 @@ namespace Masuit.Tools.Core.Html
                 sb.AppendLine(m.Result("$1"));
                 m.NextMatch();
             }
+
             return sb.ToString();
         }
+
         #endregion
 
         #region 4.3获取所有连接文本
+
         /// <summary>
         /// 4.3获取所有连接文本
         /// </summary>
@@ -393,7 +278,9 @@ namespace Masuit.Tools.Core.Html
 
             return sb.ToString();
         }
+
         #endregion
+
         #endregion
 
         #region  5、匹配页面的图片地址
@@ -406,22 +293,6 @@ namespace Masuit.Tools.Core.Html
         /// <returns></returns>
         public static string ReplaceHtmlImgSource(this string html, string imgDest) => html.Replace("<img src=\"", "<img src=\"" + imgDest + "/");
 
-        /// <summary>
-        /// 匹配页面的图片地址
-        /// </summary>
-        /// <param name="htmlCode">html代码</param>
-        /// <param name="imgHttp">要补充的http://路径信息</param>
-        public static string GetImgSrc(this string htmlCode, string imgHttp)
-        {
-            string matchVale = "";
-            string Reg = @"<img.+?>";
-            foreach (Match m in Regex.Matches(htmlCode.ToLower(), Reg))
-            {
-                matchVale += GetImg((m.Value).ToLower().Trim(), imgHttp) + "|";
-            }
-            return matchVale;
-        }
-
         /// <summary>
         /// 将src的绝对路径换成相对路径
         /// </summary>
@@ -461,6 +332,7 @@ namespace Masuit.Tools.Core.Html
             {
                 src = src.Substring(0, index);
             }
+
             return src;
         }
 
@@ -480,30 +352,13 @@ namespace Masuit.Tools.Core.Html
                 {
                     src = src.Substring(0, index);
                 }
+
                 return src;
             }
+
             return string.Empty;
         }
 
-        /// <summary>
-        /// 匹配<img src="" />中的图片路径实际链接
-        /// </summary>
-        /// <param name="imgString"><img src="" />字符串</param>
-        /// <param name="imgHttp">图片路径</param>
-        public static string GetImg(this string imgString, string imgHttp)
-        {
-            string matchVale = "";
-            string Reg = @"src=.+\.(bmp|jpg|gif|png|)";
-            foreach (Match m in Regex.Matches(imgString.ToLower(), Reg))
-            {
-                matchVale += (m.Value).ToLower().Trim().Replace("src=", "");
-            }
-            if (matchVale.IndexOf(".net") != -1 || matchVale.IndexOf(".com") != -1 || matchVale.IndexOf(".org") != -1 || matchVale.IndexOf(".cn") != -1 || matchVale.IndexOf(".cc") != -1 || matchVale.IndexOf(".info") != -1 || matchVale.IndexOf(".biz") != -1 || matchVale.IndexOf(".tv") != -1)
-            {
-                return matchVale;
-            }
-            return imgHttp + matchVale;
-        }
         #endregion
 
         #region 6、抓取远程页面内容
@@ -528,6 +383,7 @@ namespace Masuit.Tools.Core.Html
                 {
                     sb.Append(sr.ReadLine() + "\r\n");
                 }
+
                 strResult = sb.ToString();
                 hwrs.Close();
             }
@@ -535,6 +391,7 @@ namespace Masuit.Tools.Core.Html
             {
                 strResult = ee.Message;
             }
+
             return strResult;
         }
 
@@ -567,25 +424,30 @@ namespace Masuit.Tools.Core.Html
             {
                 strResult = ex.Message;
             }
+
             return strResult;
         }
+
         #endregion
 
         #region 7、压缩HTML输出
+
         /// <summary>
         /// 7.1压缩HTML输出
         /// </summary>
         /// <param name="html">html</param>
         public static string ZipHtml(this string html)
         {
-            html = Regex.Replace(html, @">\s+?<", "><");//去除HTML中的空白字符
+            html = Regex.Replace(html, @">\s+?<", "><"); //去除HTML中的空白字符
             html = Regex.Replace(html, @"\r\n\s*", "");
             html = Regex.Replace(html, @"<body([\s|\S]*?)>([\s|\S]*?)</body>", @"<body$1>$2</body>", RegexOptions.IgnoreCase);
             return html;
         }
+
         #endregion
 
         #region 8、过滤HTML标签
+
         #region 8.1过滤指定HTML标签
 
         /// <summary>
@@ -601,9 +463,12 @@ namespace Masuit.Tools.Core.Html
                 rStr = Regex.Replace(sTextStr, "<" + htmlStr + "[^>]*>", "", RegexOptions.IgnoreCase);
                 rStr = Regex.Replace(rStr, "</" + htmlStr + ">", "", RegexOptions.IgnoreCase);
             }
+
             return rStr;
         }
+
         #endregion
+
         #region 8.2过滤HTML中的不安全标签
 
         /// <summary>
@@ -617,12 +482,15 @@ namespace Masuit.Tools.Core.Html
             content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
             return content;
         }
+
         #endregion
+
         #endregion
 
         #region 转换HTML操作
 
         #region HTML转行成TEXT
+
         /// <summary>
         /// HTML转行成TEXT HtmlToTxt(string strHtml)
         /// </summary>
@@ -630,38 +498,42 @@ namespace Masuit.Tools.Core.Html
         /// <returns>普通文本</returns>
         public static string HtmlToTxt(this string strHtml)
         {
-            string[] aryReg ={
-            @"<script[^>]*?>.*?</script>",
-            @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
-            @"([\r\n])[\s]+",
-            @"&(quot|#34);",
-            @"&(amp|#38);",
-            @"&(lt|#60);",
-            @"&(gt|#62);",
-            @"&(nbsp|#160);",
-            @"&(iexcl|#161);",
-            @"&(cent|#162);",
-            @"&(pound|#163);",
-            @"&(copy|#169);",
-            @"&#(\d+);",
-            @"-->",
-            @"<!--.*\n"
+            string[] aryReg =
+            {
+                @"<script[^>]*?>.*?</script>",
+                @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
+                @"([\r\n])[\s]+",
+                @"&(quot|#34);",
+                @"&(amp|#38);",
+                @"&(lt|#60);",
+                @"&(gt|#62);",
+                @"&(nbsp|#160);",
+                @"&(iexcl|#161);",
+                @"&(cent|#162);",
+                @"&(pound|#163);",
+                @"&(copy|#169);",
+                @"&#(\d+);",
+                @"-->",
+                @"<!--.*\n"
             };
 
             string strOutput = strHtml;
-            for (int i = 0; i < aryReg.Length; i++)
+            foreach (var t in aryReg)
             {
-                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
+                Regex regex = new Regex(t, RegexOptions.IgnoreCase);
                 strOutput = regex.Replace(strOutput, string.Empty);
             }
+
             strOutput.Replace("<", "");
             strOutput.Replace(">", "");
             strOutput.Replace("\r\n", "");
             return strOutput;
         }
+
         #endregion
 
         #region 字符串转换为 Html
+
         /// <summary>
         /// 字符串转换为 HtmlStringToHtml(string str)
         /// </summary>
@@ -680,9 +552,11 @@ namespace Masuit.Tools.Core.Html
             str = str.Replace("\r\n", "<br />");
             return str;
         }
+
         #endregion
 
         #region Html转换成字符串
+
         /// <summary>
         /// html转换成字符串
         /// </summary>
@@ -700,7 +574,9 @@ namespace Masuit.Tools.Core.Html
             strHtml = Regex.Replace(strHtml, @"<\/?[^>]+>", "", RegexOptions.IgnoreCase);
             return strHtml;
         }
+
         #endregion
+
         #endregion
 
         #region 获取URL编码
@@ -713,103 +589,38 @@ namespace Masuit.Tools.Core.Html
         /// <returns>编码类型</returns>
         public static string GetEncoding(this HttpWebRequest _, string url)
         {
-            HttpWebRequest request = null;
-            HttpWebResponse response = null;
-            StreamReader reader = null;
-            try
-            {
-                request = (HttpWebRequest)WebRequest.Create(url);
-                request.Timeout = 20000;
-                request.AllowAutoRedirect = false;
-                response = (HttpWebResponse)request.GetResponse();
-                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
-                {
-                    if (response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
-                    {
-                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
-                    }
-                    else
-                    {
-                        reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
-                    }
-
-                    string html = reader.ReadToEnd();
-                    Regex regCharset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
-                    if (regCharset.IsMatch(html))
-                    {
-                        return regCharset.Match(html).Groups["charset"].Value;
-                    }
-                    else if (response.CharacterSet != string.Empty)
-                    {
-                        return response.CharacterSet;
-                    }
-                    else
-                    {
-                        return Encoding.Default.BodyName;
-                    }
-                }
-            }
-            finally
+            var request = (HttpWebRequest)WebRequest.Create(url);
+            request.Timeout = 20000;
+            request.AllowAutoRedirect = false;
+            using (var response = (HttpWebResponse)request.GetResponse())
             {
-                if (response != null)
+                if (response.StatusCode != HttpStatusCode.OK || response.ContentLength >= 1024 * 1024)
                 {
-                    response.Close();
-                    response = null;
+                    return Encoding.Default.BodyName;
                 }
-                if (reader != null)
-                    reader.Close();
-                if (request != null)
-                    request = null;
-            }
-            return Encoding.Default.BodyName;
-        }
-        #endregion
 
-        #region 判断URL是否有效
+                var reader = response.ContentEncoding.Equals("gzip") ? new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) : new StreamReader(response.GetResponseStream(), Encoding.ASCII);
 
-        /// <summary>
-        /// 判断URL是否有效
-        /// </summary>
-        /// <param name="_"></param>
-        /// <param name="url">待判断的URL,可以是网页以及图片链接等</param>
-        /// <returns>200为正确,其余为大致网页错误代码</returns>
-        public static int GetUrlError(this HttpWebRequest _, string url)
-        {
-            int num = 200;
-            try
-            {
-                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
-                ServicePointManager.Expect100Continue = false;
-                ((HttpWebResponse)request.GetResponse()).Close();
-            }
-            catch (WebException exception)
-            {
-                if (exception.Status != WebExceptionStatus.ProtocolError)
-                {
-                    return num;
-                }
-                if (exception.Message.IndexOf("500 ") > 0)
-                {
-                    return 500;
-                }
-                if (exception.Message.IndexOf("401 ") > 0)
+                string html = reader.ReadToEnd();
+                Regex regCharset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
+                if (regCharset.IsMatch(html))
                 {
-                    return 401;
+                    return regCharset.Match(html).Groups["charset"].Value;
                 }
-                if (exception.Message.IndexOf("404") > 0)
+
+                if (response.CharacterSet != string.Empty)
                 {
-                    num = 404;
+                    return response.CharacterSet;
                 }
             }
-            catch
-            {
-                num = 401;
-            }
-            return num;
+
+            return Encoding.Default.BodyName;
         }
+
         #endregion
 
         #region 返回 HTML 字符串的编码解码结果
+
         /// <summary>
         /// 返回 HTML 字符串的编码结果
         /// </summary>
@@ -829,6 +640,7 @@ namespace Masuit.Tools.Core.Html
         {
             return HttpUtility.HtmlDecode(str);
         }
+
         #endregion
 
         /// <summary>
@@ -839,7 +651,6 @@ namespace Masuit.Tools.Core.Html
         /// <returns>Cookie键值集合</returns>
         public static CookieCollection GetCookieCollection(this CookieCollection cookie, string cookieString)
         {
-            //string cookieString = "SID=ARRGy4M1QVBtTU-ymi8bL6X8mVkctYbSbyDgdH8inu48rh_7FFxHE6MKYwqBFAJqlplUxq7hnBK5eqoh3E54jqk=;Domain=.google.com;Path=/,LSID=AaMBTixN1MqutGovVSOejyb8mVkctYbSbyDgdH8inu48rh_7FFxHE6MKYwqBFAJqlhCe_QqxLg00W5OZejb_UeQ=;Domain=www.google.com;Path=/accounts";
             Regex re = new Regex("([^;,]+)=([^;,]+);Domain=([^;,]+);Path=([^;,]+)", RegexOptions.IgnoreCase);
             foreach (Match m in re.Matches(cookieString))
             {
@@ -847,6 +658,7 @@ namespace Masuit.Tools.Core.Html
                 Cookie c = new Cookie(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value, m.Groups[3].Value);
                 cookie.Add(c);
             }
+
             return cookie;
         }
 
@@ -863,6 +675,7 @@ namespace Masuit.Tools.Core.Html
 
             return regEx.Replace(HTML, "");
         }
+
         #endregion
 
         #region 获取HTML页面内制定Key的Value内容
@@ -883,8 +696,10 @@ namespace Masuit.Tools.Core.Html
             {
                 result = mc.Groups[1].Value;
             }
+
             return result;
         }
+
         #endregion
 
         /// <summary>
@@ -893,19 +708,13 @@ namespace Masuit.Tools.Core.Html
         /// <param name="str">html</param>
         public static string StrFormat(this string str)
         {
-            string str2;
-            if (str == null)
-            {
-                str2 = "";
-            }
-            else
-            {
-                str = str.Replace("\r\n", "<br />");
-                str = str.Replace("\n", "<br />");
-                str2 = str;
-            }
+            str = str.Replace("\r\n", "<br />");
+            str = str.Replace("\n", "<br />");
+            var str2 = str;
+
             return str2;
         }
+
         /// <summary>
         /// 替换html字符
         /// </summary>
@@ -919,6 +728,7 @@ namespace Masuit.Tools.Core.Html
                 strHtml = strHtml.Replace(";", "&dec");
                 return strHtml;
             }
+
             return "";
         }
 

文件差異過大導致無法顯示
+ 181 - 257
Masuit.Tools.Core/Html/HtmlTools.cs


+ 1 - 1
Masuit.Tools.Core/Logging/LogInfo.cs

@@ -1,6 +1,6 @@
 using System;
 
-namespace Masuit.Tools.Core.Logging
+namespace Masuit.Tools.Logging
 {
     /// <summary>
     /// 日志信息

+ 1 - 1
Masuit.Tools.Core/Logging/LogLevel.cs

@@ -1,4 +1,4 @@
-namespace Masuit.Tools.Core.Logging
+namespace Masuit.Tools.Logging
 {
     public enum LogLevel
     {

+ 51 - 37
Masuit.Tools.Core/Logging/LogManager.cs

@@ -6,8 +6,9 @@ using System.Linq;
 using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading.Tasks;
+using static System.DateTime;
 
-namespace Masuit.Tools.Core.Logging
+namespace Masuit.Tools.Logging
 {
     /// <summary>
     /// 日志组件
@@ -20,6 +21,7 @@ namespace Masuit.Tools.Core.Logging
         /// 自定义事件
         /// </summary>
         public static event Action<LogInfo> Event;
+
         static LogManager()
         {
             var writeTask = new Task(obj =>
@@ -39,11 +41,17 @@ namespace Masuit.Tools.Core.Logging
                         }
                         else
                         {
-                            logArr = new[] { logPath, logMergeContent };
+                            logArr = new[]
+                            {
+                                logPath,
+                                logMergeContent
+                            };
                             temp.Add(logArr);
                         }
+
                         LogQueue.TryDequeue(out Tuple<string, string> _);
                     }
+
                     foreach (var item in temp)
                     {
                         WriteText(item[0], item[1]);
@@ -60,21 +68,24 @@ namespace Masuit.Tools.Core.Logging
         /// </summary>
         public static string LogDirectory
         {
-            get => AppContext.BaseDirectory + "logs";
-            set { }
+            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(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}  {info}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}  {info}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Info,
                 Message = info,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId
             };
             Event?.Invoke(log);
@@ -87,12 +98,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="info"></param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source}  {info}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Info,
                 Message = info,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source
             };
@@ -106,12 +117,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="info"></param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(info).ToUpper()}   {source.FullName}  {info}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Info,
                 Message = info,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source.FullName
             };
@@ -124,12 +135,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="debug">异常对象</param>
         public static void Debug(string debug)
         {
-            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{DateTime.Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {debug}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {debug}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Debug,
                 Message = debug,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId
             };
             Event?.Invoke(log);
@@ -142,12 +153,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="debug">异常对象</param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source}  {debug}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Debug,
                 Message = debug,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source
             };
@@ -161,12 +172,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="debug">异常对象</param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(debug).ToUpper()}   {source.FullName}  {debug}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Debug,
                 Message = debug,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source.FullName
             };
@@ -179,12 +190,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="error">异常对象</param>
         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}"));
+            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}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Error,
                 Message = error.Message,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = error.Source,
                 Exception = error,
@@ -200,12 +211,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="error">异常对象</param>
         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}"));
+            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}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Error,
                 Message = error.Message,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source.FullName,
                 Exception = error,
@@ -221,12 +232,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="error">异常信息</param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source.FullName}  {error}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Error,
                 Message = error,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source.FullName,
                 //Exception = error,
@@ -242,12 +253,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="error">异常对象</param>
         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}"));
+            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}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Error,
                 Message = error.Message,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source,
                 Exception = error,
@@ -263,12 +274,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="error">异常信息</param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(error).ToUpper()}   {source}  {error}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Error,
                 Message = error,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source,
                 //Exception = error,
@@ -283,12 +294,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="fatal">异常对象</param>
         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}"));
+            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}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Fatal,
                 Message = fatal.Message,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = fatal.Source,
                 Exception = fatal,
@@ -304,12 +315,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="fatal">异常对象</param>
         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}"));
+            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}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Fatal,
                 Message = fatal.Message,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source.FullName,
                 Exception = fatal,
@@ -325,12 +336,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="fatal">异常对象</param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source.FullName}  {fatal}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Fatal,
                 Message = fatal,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source.FullName,
                 //Exception = fatal,
@@ -346,12 +357,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="fatal">异常对象</param>
         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}"));
+            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}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Fatal,
                 Message = fatal.Message,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source,
                 Exception = fatal,
@@ -367,12 +378,12 @@ namespace Masuit.Tools.Core.Logging
         /// <param name="fatal">异常对象</param>
         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}"));
+            LogQueue.Enqueue(new Tuple<string, string>(GetLogPath(), $"{Now}   [{Thread.CurrentThread.ManagedThreadId}]   {nameof(fatal).ToUpper()}   {source}  {fatal}"));
             LogInfo log = new LogInfo()
             {
                 LogLevel = LogLevel.Fatal,
                 Message = fatal,
-                Time = DateTime.Now,
+                Time = Now,
                 ThreadId = Thread.CurrentThread.ManagedThreadId,
                 Source = source,
                 ExceptionType = fatal.GetType().Name
@@ -388,8 +399,9 @@ namespace Masuit.Tools.Core.Logging
             {
                 Directory.CreateDirectory(logDir);
             }
+
             string extension = ".log";
-            string fileNameNotExt = DateTime.Now.ToString("yyyyMMdd");
+            string fileNameNotExt = Now.ToString("yyyyMMdd");
             string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension);
             List<string> filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList();
 
@@ -415,6 +427,7 @@ namespace Masuit.Tools.Core.Logging
                 string newFileName = string.Concat(fileNameNotExt, $"({0})", extension);
                 newFilePath = Path.Combine(logDir, newFileName);
             }
+
             return newFilePath;
         }
 
@@ -426,6 +439,7 @@ namespace Masuit.Tools.Core.Logging
                 {
                     File.CreateText(logPath).Close();
                 }
+
                 using (StreamWriter sw = File.AppendText(logPath))
                 {
                     sw.Write(logContent);

+ 11 - 15
Masuit.Tools.Core/Media/ImageUtilities.cs

@@ -8,7 +8,7 @@ using System.Net.Http;
 using System.Net.Http.Headers;
 using System.Threading.Tasks;
 
-namespace Masuit.Tools.Core.Media
+namespace Masuit.Tools.Media
 {
     /// <summary>
     /// 图片处理
@@ -28,7 +28,6 @@ namespace Masuit.Tools.Core.Media
         /// <param name="quality">质量(范围0-100)</param>
         public static void CutForSquare(this Stream fromFile, string fileSaveUrl, int side, int quality)
         {
-            var aliceBlue = Color.AliceBlue;
             //创建目录
             string dir = Path.GetDirectoryName(fileSaveUrl);
             if (!Directory.Exists(dir))
@@ -243,7 +242,7 @@ namespace Masuit.Tools.Core.Media
                     ImageCodecInfo ici = null;
                     foreach (ImageCodecInfo i in icis)
                     {
-                        if ((i.MimeType == "image/jpeg") || (i.MimeType == "image/bmp") || (i.MimeType == "image/png") || (i.MimeType == "image/gif"))
+                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                             ici = i;
                     }
 
@@ -482,12 +481,13 @@ namespace Masuit.Tools.Core.Media
         /// <returns>剪裁后的Bitmap</returns>
         public static Bitmap CutImage(this Bitmap b, Rectangle rec)
         {
-            if (b == null)
-                return null;
             int w = b.Width;
             int h = b.Height;
             if ((rec.X >= w) || (rec.Y >= h))
+            {
                 return null;
+            }
+
             if (rec.X + rec.Width > w)
                 rec.Width = w - rec.X;
             if (rec.Y + rec.Height > h)
@@ -840,12 +840,11 @@ namespace Masuit.Tools.Core.Media
         {
             Bitmap bm = new Bitmap(width, height); //初始化一个记录经过处理后的图片对象
             int x, y; //x、y是循环次数,后面三个是记录红绿蓝三个值的
-            Color pixel;
             for (x = 0; x < width; x++)
             {
                 for (y = 0; y < height; y++)
                 {
-                    pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                    var pixel = mybm.GetPixel(x, y);
                     var resultR = pixel.R + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
                     var resultG = pixel.G + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
                     var resultB = pixel.B + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
@@ -998,12 +997,11 @@ namespace Masuit.Tools.Core.Media
             using (Bitmap bm = new Bitmap(width, height))
             {
                 int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-                Color pixel;
                 for (y = height - 1; y >= 0; y--)
                 {
                     for (x = width - 1, z = 0; x >= 0; x--)
                     {
-                        pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                        var pixel = mybm.GetPixel(x, y);
                         bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                     }
                 }
@@ -1028,12 +1026,11 @@ namespace Masuit.Tools.Core.Media
             using (bm)
             {
                 int x, y, z;
-                Color pixel;
                 for (x = 0; x < width; x++)
                 {
                     for (y = height - 1, z = 0; y >= 0; y--)
                     {
-                        pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                        var pixel = mybm.GetPixel(x, y);
                         bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                     }
                 }
@@ -1118,14 +1115,13 @@ namespace Masuit.Tools.Core.Media
             Bitmap bm = new Bitmap(width, height);
             using (bm)
             {
-                int x, y, result; //x,y是循环次数,result是记录处理后的像素值
-                Color pixel;
+                int x, y; //x,y是循环次数
                 for (x = 0; x < width; x++)
                 {
                     for (y = 0; y < height; y++)
                     {
-                        pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
-                        result = (pixel.R + pixel.G + pixel.B) / 3; //取红绿蓝三色的平均
+                        var pixel = mybm.GetPixel(x, y);
+                        var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素
                         bm.SetPixel(x, y, Color.FromArgb(result, result, result));
                     }
                 }

+ 27 - 1
Masuit.Tools.Core/Net/FtpClient.cs

@@ -50,6 +50,7 @@ namespace Masuit.Tools.Net
                 {
                     throw new Exception("ftp下载目标服务器地址未设置!");
                 }
+
                 Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
                 var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
                 ftpsize.UseBinary = true;
@@ -61,6 +62,7 @@ namespace Masuit.Tools.Net
                     ftpsize.Credentials = new NetworkCredential(Username, Password);
                     reqFtp.Credentials = new NetworkCredential(Username, Password);
                 }
+
                 ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                 using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
                 {
@@ -111,6 +113,7 @@ namespace Masuit.Tools.Net
                 {
                     throw new Exception("ftp下载目标服务器地址未设置!");
                 }
+
                 Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
                 var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
                 ftpsize.UseBinary = true;
@@ -124,6 +127,7 @@ namespace Masuit.Tools.Net
                     ftpsize.Credentials = new NetworkCredential(Username, Password);
                     reqFtp.Credentials = new NetworkCredential(Username, Password);
                 }
+
                 ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                 using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
                 {
@@ -175,8 +179,10 @@ namespace Masuit.Tools.Net
                         size = outputStream.Length;
                     }
                 }
+
                 BrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
             }
+
             Download(remoteFileName, localFileName, ifCredential, updateProgress);
         }
 
@@ -196,6 +202,7 @@ namespace Masuit.Tools.Net
             {
                 throw new Exception("ftp上传目标服务器地址未设置!");
             }
+
             Uri uri = new Uri("ftp://" + FtpServer + "/" + finfo.Name);
             var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
             reqFtp.KeepAlive = false;
@@ -239,6 +246,7 @@ namespace Masuit.Tools.Net
             {
                 remoteFilepath = "";
             }
+
             string newFileName;
             FileInfo fileInf = new FileInfo(localFullPath);
             long allbye = fileInf.Length;
@@ -251,11 +259,13 @@ namespace Masuit.Tools.Net
                 newFileName = fileInf.Name.Replace("#", "#");
                 newFileName = RemoveSpaces(newFileName);
             }
+
             long startfilesize = GetFileSize(newFileName, remoteFilepath);
             if (startfilesize >= allbye)
             {
                 return false;
             }
+
             long startbye = startfilesize;
             //更新进度 
             updateProgress?.Invoke((int)allbye, (int)startfilesize); //更新进度条 
@@ -269,6 +279,7 @@ namespace Masuit.Tools.Net
             {
                 uri = "ftp://" + FtpServer + "/" + remoteFilepath + "/" + newFileName;
             }
+
             // 根据uri创建FtpWebRequest对象 
             var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri));
             // ftp用户名和密码 
@@ -304,6 +315,7 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
+
             return true;
         }
 
@@ -324,6 +336,7 @@ namespace Masuit.Tools.Net
                     a += c.ToString();
                 }
             }
+
             return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
         }
 
@@ -347,6 +360,7 @@ namespace Masuit.Tools.Net
                 {
                     uri = "ftp://" + FtpServer + "/" + remoteFilepath + "/" + fi.Name;
                 }
+
                 var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
                 reqFtp.KeepAlive = false;
                 reqFtp.UseBinary = true;
@@ -387,9 +401,11 @@ namespace Masuit.Tools.Net
                         result.Append("\n");
                         line = reader.ReadLine();
                     }
+
                     result.Remove(result.ToString().LastIndexOf("\n", StringComparison.Ordinal), 1);
                 }
             }
+
             return result.ToString().Split('\n');
         }
 
@@ -425,11 +441,14 @@ namespace Masuit.Tools.Net
                             result.Append(line);
                             result.Append("\n");
                         }
+
                         line = reader.ReadLine();
                     }
+
                     result.Remove(result.ToString().LastIndexOf('\n'), 1);
                 }
             }
+
             return result.ToString().Split('\n');
         }
 
@@ -459,7 +478,11 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
-            char[] n = { '\n' };
+
+            char[] n =
+            {
+                '\n'
+            };
             return m.Split(n);
         }
 
@@ -553,6 +576,7 @@ namespace Masuit.Tools.Net
                         return true;
                     }
                 }
+
                 return false;
             }
             catch
@@ -575,6 +599,7 @@ namespace Masuit.Tools.Net
                     return true;
                 }
             }
+
             return false;
         }
 
@@ -642,6 +667,7 @@ namespace Masuit.Tools.Net
             {
                 _ftpRemotePath += directoryName + "/";
             }
+
             FtpUri = "ftp://" + FtpServer + "/" + _ftpRemotePath + "/";
         }
 

+ 43 - 15
Masuit.Tools.Core/Net/MultiThreadDownloader.cs

@@ -7,7 +7,7 @@ using System.Net;
 using System.Threading;
 using System.Threading.Tasks;
 
-namespace Masuit.Tools.Core.Net
+namespace Masuit.Tools.Net
 {
     /// <summary>
     /// 文件合并改变事件
@@ -21,19 +21,24 @@ namespace Masuit.Tools.Core.Net
     /// </summary>
     public class MultiThreadDownloader
     {
-        #region Variables
+        #region 变量
+
         /// <summary>
         /// 总下载进度更新事件
         /// </summary>
         public event EventHandler TotalProgressChanged;
+
         /// <summary>
         /// 文件合并事件
         /// </summary>
         public event FileMergeProgressChangedEventHandler FileMergeProgressChanged;
+
         private readonly AsyncOperation _aop;
+
         #endregion
 
-        #region DownloadManager
+        #region 下载管理器
+
         public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts)
         {
             _url = sourceUrl;
@@ -43,16 +48,19 @@ namespace Masuit.Tools.Core.Net
             _aop = AsyncOperationManager.CreateOperation(null);
             FilePath = savePath;
         }
+
         public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, savePath, numOfParts)
         {
             TempFileDirectory = Environment.GetEnvironmentVariable("temp");
         }
+
         public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts)
         {
         }
+
         #endregion
 
-        #region Events
+        #region 事件
 
         private void temp_DownloadPartCompleted(object sender, EventArgs e)
         {
@@ -81,6 +89,7 @@ namespace Masuit.Tools.Core.Net
                 WaitOrResumeAll(PartialDownloaderList, false);
                 return;
             }
+
             PartialDownloaderList[0].To = from - 1;
 
             WaitOrResumeAll(PartialDownloaderList, false);
@@ -109,9 +118,11 @@ namespace Masuit.Tools.Core.Net
                 }
             }
         }
+
         #endregion
 
-        #region Helpers
+        #region 方法
+
         void CreateFirstPartitions()
         {
             Size = GetContentLength(_url, ref _rangeAllowed, ref _url);
@@ -131,6 +142,7 @@ namespace Masuit.Tools.Core.Net
                 temp.Start();
             }
         }
+
         void MergeParts()
         {
             List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
@@ -156,10 +168,12 @@ namespace Masuit.Tools.Core.Net
                             }
                         }
                     }
+
                     File.Delete(item.FullPath);
                 }
             }
         }
+
         PartialDownloader CreateNewPd(int order, int parts, long contentLength)
         {
             int division = (int)contentLength / parts;
@@ -169,6 +183,7 @@ namespace Masuit.Tools.Core.Net
             end += (order == parts - 1) ? remaining : 0;
             return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), start, end, true);
         }
+
         public static void WaitOrResumeAll(List<PartialDownloader> list, bool wait)
         {
             foreach (PartialDownloader item in list)
@@ -199,11 +214,13 @@ namespace Masuit.Tools.Core.Net
                 }
             }
         }
+
         //Sorts the downloader by From property to merge the parts
         public static List<PartialDownloader> SortPDsByFrom(List<PartialDownloader> list)
         {
             return list.OrderBy(x => x.From).ToList();
         }
+
         public static void OrderByRemaining(List<PartialDownloader> list)
         {
             BubbleSort(list);
@@ -214,17 +231,26 @@ namespace Masuit.Tools.Core.Net
             HttpWebRequest 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;
-            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
-            redirectedUrl = resp.ResponseUri.OriginalString;
-            long 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();
+            long ctl;
+            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
+            {
+                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();
+            }
+
             req.Abort();
             return ctl;
         }
+
         #endregion
 
-        #region Public Methods
+        #region 公共方法
 
         /// <summary>
         /// 暂停下载
@@ -273,21 +299,24 @@ namespace Masuit.Tools.Core.Net
                 }
             }
         }
+
         #endregion
 
-        #region Property Variables
+        #region 属性
 
         private string _url;
         private bool _rangeAllowed;
 
         #endregion
 
-        #region Properties
+        #region 公共属性
+
         public bool RangeAllowed
         {
             get => _rangeAllowed;
             set => _rangeAllowed = value;
         }
+
         public string TempFileDirectory { get; set; }
 
         public string Url
@@ -310,6 +339,5 @@ namespace Masuit.Tools.Core.Net
         public string FilePath { get; set; }
 
         #endregion
-
     }
-}
+}

+ 26 - 7
Masuit.Tools.Core/Net/PartialDownloader.cs

@@ -6,11 +6,12 @@ using System.Linq;
 using System.Net;
 using System.Threading;
 
-namespace Masuit.Tools.Core.Net
+namespace Masuit.Tools.Net
 {
     public class PartialDownloader
     {
         #region Variables
+
         public event EventHandler DownloadPartCompleted;
         public event EventHandler DownloadPartProgressChanged;
         public event EventHandler DownloadPartStopped;
@@ -23,9 +24,11 @@ namespace Masuit.Tools.Core.Net
         readonly int[] _lastSpeeds;
         int _counter;
         bool _stop, _wait;
+
         #endregion
 
         #region PartialDownloader
+
         public PartialDownloader(string url, string dir, string fileGuid, int from, int to, bool rangeAllowed)
         {
             _from = from;
@@ -37,12 +40,15 @@ namespace Masuit.Tools.Core.Net
             _lastSpeeds = new int[10];
             _stp = new Stopwatch();
         }
+
         #endregion
 
         void DownloadProcedure()
         {
             _file = new FileStream(FullPath, FileMode.Create, FileAccess.ReadWrite);
+
             #region Request-Response
+
             _req = WebRequest.Create(_url) as HttpWebRequest;
             if (_req != null)
             {
@@ -83,16 +89,19 @@ namespace Masuit.Tools.Core.Net
                         }
 
                         if (_totalBytesRead + bytesRead > _contentLength)
-                            bytesRead = (int)(_contentLength - _totalBytesRead);
+                            bytesRead = (int) (_contentLength - _totalBytesRead);
                         _file.Write(buffer, 0, bytesRead);
                         _totalBytesRead += bytesRead;
-                        _lastSpeeds[_counter] = (int)(_totalBytesRead / Math.Ceiling(_stp.Elapsed.TotalSeconds));
+                        _lastSpeeds[_counter] = (int) (_totalBytesRead / Math.Ceiling(_stp.Elapsed.TotalSeconds));
                         _counter = (_counter >= 9) ? 0 : _counter + 1;
-                        int tempProgress = (int)(_totalBytesRead * 100 / _contentLength);
+                        int tempProgress = (int) (_totalBytesRead * 100 / _contentLength);
                         if (_progress != tempProgress)
                         {
                             _progress = tempProgress;
-                            _aop.Post(state => { DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty); }, null);
+                            _aop.Post(state =>
+                            {
+                                DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty);
+                            }, null);
                         }
 
                         if (_stop || (_rangeAllowed && _totalBytesRead == _contentLength))
@@ -114,9 +123,11 @@ namespace Masuit.Tools.Core.Net
             }
 
             _stp.Stop();
+
             #endregion
 
             #region Fire Events
+
             if (!_stop && DownloadPartCompleted != null)
                 _aop.Post(state =>
                 {
@@ -131,6 +142,7 @@ namespace Masuit.Tools.Core.Net
         }
 
         #region Public Methods
+
         public void Start()
         {
             _stop = false;
@@ -142,18 +154,22 @@ namespace Masuit.Tools.Core.Net
         {
             _stop = true;
         }
+
         //Wait is used when repartitiate a partition securely in this project
         public void Wait()
         {
             _wait = true;
         }
+
         public void ResumeAfterWait()
         {
             _wait = false;
         }
+
         #endregion
 
         #region Property Variables
+
         private readonly int _from;
         private int _to;
         private readonly string _url;
@@ -164,9 +180,11 @@ namespace Masuit.Tools.Core.Net
         private readonly string _directory;
         private int _progress;
         private bool _completed;
+
         #endregion
 
         #region Properties
+
         public bool Stopped => _stop;
 
         public bool Completed => _completed;
@@ -199,7 +217,7 @@ namespace Masuit.Tools.Core.Net
 
         public int CurrentPosition => _from + _totalBytesRead - 1;
 
-        public int RemainingBytes => (int)(_contentLength - _totalBytesRead);
+        public int RemainingBytes => (int) (_contentLength - _totalBytesRead);
 
         public string FullPath => Path.Combine(_directory, _fileGuid);
 
@@ -215,6 +233,7 @@ namespace Masuit.Tools.Core.Net
                 return totalSpeeds / 10;
             }
         }
+
         #endregion
     }
-}
+}

+ 20 - 11
Masuit.Tools.Core/Net/SocketClient.cs

@@ -7,7 +7,7 @@ using System.Runtime.Serialization.Formatters.Binary;
 using System.Text;
 using System.Threading;
 
-namespace Masuit.Tools.Core.Net
+namespace Masuit.Tools.Net
 {
     /// <summary>
     /// Socket客户端操作类
@@ -36,7 +36,7 @@ namespace Masuit.Tools.Core.Net
                 Socket socket = listener.AcceptSocket();
                 return socket;
             }
-            catch
+            catch (Exception)
             {
                 return null;
             }
@@ -54,7 +54,7 @@ namespace Masuit.Tools.Core.Net
                 TcpClient client = listener.AcceptTcpClient();
                 return client.GetStream();
             }
-            catch
+            catch (Exception)
             {
                 return null;
             }
@@ -77,7 +77,7 @@ namespace Masuit.Tools.Core.Net
                 tcpclient.Connect(ipendpoint);
                 return tcpclient.Client;
             }
-            catch
+            catch (Exception)
             {
                 return null;
             }
@@ -97,7 +97,7 @@ namespace Masuit.Tools.Core.Net
                 tcpclient.Connect(ipadd, port);
                 return tcpclient.Client;
             }
-            catch
+            catch (Exception)
             {
                 return null;
             }
@@ -116,7 +116,7 @@ namespace Masuit.Tools.Core.Net
                 tcpclient.Connect(ipendpoint);
                 return tcpclient.GetStream();
             }
-            catch
+            catch (Exception)
             {
                 return null;
             }
@@ -136,7 +136,7 @@ namespace Masuit.Tools.Core.Net
                 tcpclient.Connect(ipadd, port);
                 return tcpclient.GetStream();
             }
-            catch
+            catch (Exception)
             {
                 return null;
             }
@@ -165,6 +165,7 @@ namespace Masuit.Tools.Core.Net
                 offset += recv;
                 dataleft -= recv;
             }
+
             return msg;
         }
 
@@ -225,11 +226,13 @@ namespace Masuit.Tools.Core.Net
                     if (mark == 10)
                         break;
                 }
+
                 if (offset == length)
                     break;
             }
+
             stream.Seek(0, SeekOrigin.Begin); //必须要这个 或者stream.Position = 0;
-            T t = (T)format.Deserialize(stream);
+            T t = (T) format.Deserialize(stream);
             stream.Close();
             return t;
         }
@@ -252,7 +255,6 @@ namespace Masuit.Tools.Core.Net
                 string savepath = GetPath(path, filename); //得到文件路径
                 //缓冲区
                 byte[] file = new byte[m_maxpacket];
-                int count = 0; //每次接收的实际长度
                 int receivedata = m_maxpacket; //每次要接收的长度
                 long offset = 0; //循环接收的总长度
                 long lastdata = size; //剩余多少还没接收
@@ -264,7 +266,7 @@ namespace Masuit.Tools.Core.Net
                         {
                             if (lastdata < receivedata)
                                 receivedata = Convert.ToInt32(lastdata);
-                            count = socket.Receive(file, 0, receivedata, SocketFlags.None);
+                            var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
                             if (count > 0)
                             {
                                 fs.Write(file, 0, count);
@@ -278,6 +280,7 @@ namespace Masuit.Tools.Core.Net
                                 if (mark == 10)
                                     break;
                             }
+
                             //接收进度
                             if (progress != null)
                                 progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
@@ -288,9 +291,11 @@ namespace Masuit.Tools.Core.Net
                                 break;
                             }
                         }
+
                     fs.Close();
                 }
             }
+
             return ret;
         }
 
@@ -345,6 +350,7 @@ namespace Masuit.Tools.Core.Net
         private static int i;
 
         private static string markPath = string.Empty;
+
         /// <summary>
         /// 得到文件路径(防止有文件名重复)
         ///  如:aaa.txt已经在directory目录下存在,则会得到文件aaa(1).txt
@@ -352,7 +358,6 @@ namespace Masuit.Tools.Core.Net
         /// <param name="directory">目录名</param>
         /// <param name="file">文件名</param>
         /// <returns>文件路径</returns>
-
         public static string GetPath(string directory, string file)
         {
             if (markPath == string.Empty)
@@ -365,6 +370,7 @@ namespace Masuit.Tools.Core.Net
                 string extension = Path.GetExtension(markPath);
                 return GetPath(directory, filename + extension);
             }
+
             i = 0;
             markPath = string.Empty;
             return path;
@@ -398,6 +404,7 @@ namespace Masuit.Tools.Core.Net
                 if (offset == size)
                     break;
             }
+
             return offset;
         }
 
@@ -493,6 +500,7 @@ namespace Masuit.Tools.Core.Net
                             if (mark == 10)
                                 break;
                         }
+
                         if (progress != null)
                             progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
                         if (offset == length)
@@ -501,6 +509,7 @@ namespace Masuit.Tools.Core.Net
                     }
                 }
             }
+
             return ret;
         }
 

+ 49 - 10
Masuit.Tools.Core/Reflection/ReflectHelper.cs

@@ -1,5 +1,6 @@
 using System;
 using System.ComponentModel;
+using System.Drawing;
 using System.IO;
 using System.Reflection;
 using System.Resources;
@@ -13,6 +14,7 @@ namespace Masuit.Tools.Reflection
     public static class ReflectHelper
     {
         #region 成员读写
+
         /// <summary>
         /// 获取实体相关属性的值
         /// </summary>
@@ -30,11 +32,14 @@ namespace Masuit.Tools.Reflection
                     objRet = descriptor.GetValue(obj);
                 }
             }
+
             return objRet;
         }
+
         #endregion
 
         #region 方法调用
+
         /// <summary>
         /// 直接调用内部对象的方法/函数或获取属性(支持重载调用)
         /// </summary>
@@ -52,6 +57,7 @@ namespace Masuit.Tools.Reflection
             {
                 throw new InvalidProgramException(string.Concat("函数/方法 [", funName, "] 在指定类型(", refType.ToString(), ")中不存在!"));
             }
+
             MethodInfo targetMethod = null;
             StringBuilder pb = new StringBuilder();
             foreach (MemberInfo mi in mis)
@@ -61,10 +67,13 @@ namespace Masuit.Tools.Reflection
                     if (mi.MemberType == MemberTypes.Property)
                     {
                         #region 调用属性方法Get
+
                         targetMethod = ((PropertyInfo)mi).GetGetMethod();
                         break;
+
                         #endregion
                     }
+
                     throw new InvalidProgramException(string.Concat("[", funName, "] 不是有效的函数/属性方法!"));
                 }
 
@@ -81,6 +90,7 @@ namespace Masuit.Tools.Reflection
                     int paramIdx = 0;
 
                     #region 检查数据类型 设置validParamsType是否有效
+
                     foreach (ParameterInfo pi in pis)
                     {
                         pb.AppendFormat("Parameter {0}: Type={1}, Name={2}\n", paramIdx, pi.ParameterType, pi.Name);
@@ -89,6 +99,7 @@ namespace Masuit.Tools.Reflection
                         if (funParams[paramIdx] != null && pi.ParameterType != typeof(object) && (pi.ParameterType != funParams[paramIdx].GetType()))
                         {
                             #region 检查类型是否兼容
+
                             try
                             {
                                 funParams[paramIdx] = Convert.ChangeType(funParams[paramIdx], pi.ParameterType);
@@ -97,11 +108,15 @@ namespace Masuit.Tools.Reflection
                             {
                                 paramFlag = false;
                             }
+
                             #endregion
+
                             //break;
                         }
+
                         ++paramIdx;
                     }
+
                     #endregion
 
                     bool validParamsType;
@@ -113,32 +128,38 @@ namespace Masuit.Tools.Reflection
                     {
                         continue;
                     }
+
                     if (validParamsLen && validParamsType)
                     {
                         targetMethod = curMethod;
                         break;
                     }
                 }
+
                 #endregion
             }
 
             if (targetMethod != null)
             {
-                object objReturn = null;
+                object objReturn;
+
                 #region 兼顾效率和兼容重载函数调用
+
                 try
                 {
                     object objInstance = Activator.CreateInstance(refType, objInitial);
-                    objReturn = targetMethod.Invoke(objInstance, BindingFlags.InvokeMethod, Type.DefaultBinder, funParams,
-                        System.Globalization.CultureInfo.InvariantCulture);
+                    objReturn = targetMethod.Invoke(objInstance, BindingFlags.InvokeMethod, Type.DefaultBinder, funParams, System.Globalization.CultureInfo.InvariantCulture);
                 }
                 catch (Exception)
                 {
                     objReturn = refType.InvokeMember(funName, BindingFlags.InvokeMethod, Type.DefaultBinder, null, funParams);
                 }
+
                 #endregion
+
                 return (T)objReturn;
             }
+
             throw new InvalidProgramException(string.Concat("函数/方法 [", refType.ToString(), ".", funName, "(args ...) ] 参数长度和数据类型不正确!\n 引用参数信息参考:\n", pb.ToString()));
         }
 
@@ -154,9 +175,24 @@ namespace Masuit.Tools.Reflection
         {
             return InvokeMethodOrGetProperty<T>(refType, funName, null, funParams);
         }
+
         #endregion
 
         #region 资源获取
+
+        /// <summary>
+        /// 获取程序集资源的位图资源
+        /// </summary>
+        /// <param name="assemblyType">程序集中的某一对象类型</param>
+        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
+        /// <param name="imageName">资源项名称</param>
+        public static Bitmap LoadBitmap(this Type assemblyType, string resourceHolder, string imageName)
+        {
+            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
+            var rm = new ResourceManager(resourceHolder, thisAssembly);
+            return (Bitmap)rm.GetObject(imageName);
+        }
+
         /// <summary>
         ///  获取程序集资源的文本资源
         /// </summary>
@@ -175,20 +211,23 @@ namespace Masuit.Tools.Reflection
         /// </summary>
         /// <param name="assemblyType">程序集中的某一对象类型</param>
         /// <param name="charset">字符集编码</param>
-        /// <param name="ResName">嵌入资源相对路径</param>
+        /// <param name="resName">嵌入资源相对路径</param>
         /// <returns>如没找到该资源则返回空字符</returns>
-        public static string GetManifestString(this Type assemblyType, string charset, string ResName)
+        public static string GetManifestString(this Type assemblyType, string charset, string resName)
         {
             Assembly asm = Assembly.GetAssembly(assemblyType);
-            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace,
-                ".", ResName.Replace("/", ".")));
-            if (st == null) { return ""; }
+            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
+            if (st == null)
+            {
+                return "";
+            }
+
             int iLen = (int)st.Length;
             byte[] bytes = new byte[iLen];
             st.Read(bytes, 0, iLen);
             return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
         }
-        #endregion
 
+        #endregion
     }
-}
+}

+ 43 - 26
Masuit.Tools.Core/Reflection/ReflectionUtil.cs

@@ -1,5 +1,6 @@
 using System;
 using System.ComponentModel;
+using System.Drawing;
 using System.IO;
 using System.Reflection;
 using System.Resources;
@@ -13,6 +14,7 @@ namespace Masuit.Tools.Reflection
     public static class ReflectionUtil
     {
         #region 属性字段设置
+
 #pragma warning disable 1591
         public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
 #pragma warning restore 1591
@@ -138,19 +140,14 @@ namespace Masuit.Tools.Reflection
                 throw new ArgumentNullException(nameof(value));
             }
 
-            string text1;
-
             FieldInfo fi = value.GetType().GetField(value.ToString());
-
-            DescriptionAttribute[] attributes =
-                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
-
-            text1 = (attributes.Length > 0) ? attributes[0].Description : value.ToString();
-
+            DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
+            var text1 = (attributes.Length > 0) ? attributes[0].Description : value.ToString();
             if ((args != null) && (args.Length > 0))
             {
                 return string.Format(null, text1, args);
             }
+
             return text1;
         }
 
@@ -184,19 +181,19 @@ namespace Masuit.Tools.Reflection
 
             if (member.IsDefined(typeof(DescriptionAttribute), false))
             {
-                DescriptionAttribute[] attributes =
-                    (DescriptionAttribute[])member.GetCustomAttributes(typeof(DescriptionAttribute), false);
+                DescriptionAttribute[] attributes = (DescriptionAttribute[]) member.GetCustomAttributes(typeof(DescriptionAttribute), false);
                 text1 = attributes[0].Description;
             }
             else
             {
-                return System.String.Empty;
+                return string.Empty;
             }
 
             if ((args != null) && (args.Length > 0))
             {
-                return System.String.Format(null, text1, args);
+                return string.Format(null, text1, args);
             }
+
             return text1;
         }
 
@@ -220,15 +217,18 @@ namespace Masuit.Tools.Reflection
             {
                 throw new ArgumentNullException(nameof(attributeType));
             }
+
             if (assembly == null)
             {
                 throw new ArgumentNullException(nameof(assembly));
             }
+
             if (assembly.IsDefined(attributeType, false))
             {
                 object[] attributes = assembly.GetCustomAttributes(attributeType, false);
                 return attributes[0];
             }
+
             return null;
         }
 
@@ -254,18 +254,16 @@ namespace Masuit.Tools.Reflection
         /// </returns>
         public static object GetAttribute(this Type attributeType, MemberInfo type, bool searchParent)
         {
-            if (attributeType == null)
-            {
-                return null;
-            }
             if (type == null)
             {
                 return null;
             }
+
             if (!(attributeType.IsSubclassOf(typeof(Attribute))))
             {
                 return null;
             }
+
             if (type.IsDefined(attributeType, searchParent))
             {
                 object[] attributes = type.GetCustomAttributes(attributeType, searchParent);
@@ -275,6 +273,7 @@ namespace Masuit.Tools.Reflection
                     return attributes[0];
                 }
             }
+
             return null;
         }
 
@@ -304,18 +303,17 @@ namespace Masuit.Tools.Reflection
             {
                 return null;
             }
-            if (attributeType == null)
-            {
-                return null;
-            }
+
             if (!(attributeType.IsSubclassOf(typeof(Attribute))))
             {
                 return null;
             }
+
             if (type.IsDefined(attributeType, false))
             {
                 return type.GetCustomAttributes(attributeType, searchParent);
             }
+
             return null;
         }
 
@@ -335,6 +333,19 @@ namespace Masuit.Tools.Reflection
             return asm.GetManifestResourceStream(resourceName);
         }
 
+        /// <summary>
+        /// 获取程序集资源的位图资源
+        /// </summary>
+        /// <param name="assemblyType">程序集中的某一对象类型</param>
+        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
+        /// <param name="imageName">资源项名称</param>
+        public static Bitmap LoadBitmap(this Type assemblyType, string resourceHolder, string imageName)
+        {
+            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
+            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
+            return (Bitmap) rm.GetObject(imageName);
+        }
+
         /// <summary>
         ///  获取程序集资源的文本资源
         /// </summary>
@@ -353,15 +364,18 @@ namespace Masuit.Tools.Reflection
         /// </summary>
         /// <param name="assemblyType">程序集中的某一对象类型</param>
         /// <param name="charset">字符集编码</param>
-        /// <param name="ResName">嵌入资源相对路径</param>
+        /// <param name="resName">嵌入资源相对路径</param>
         /// <returns>如没找到该资源则返回空字符</returns>
-        public static string GetManifestString(this Type assemblyType, string charset, string ResName)
+        public static string GetManifestString(this Type assemblyType, string charset, string resName)
         {
             Assembly asm = Assembly.GetAssembly(assemblyType);
-            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace,
-                ".", ResName.Replace("/", ".")));
-            if (st == null) { return ""; }
-            int iLen = (int)st.Length;
+            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
+            if (st == null)
+            {
+                return "";
+            }
+
+            int iLen = (int) st.Length;
             byte[] bytes = new byte[iLen];
             st.Read(bytes, 0, iLen);
             return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
@@ -370,6 +384,7 @@ namespace Masuit.Tools.Reflection
         #endregion
 
         #region 创建对应实例
+
         /// <summary>
         /// 创建对应实例
         /// </summary>
@@ -386,6 +401,7 @@ namespace Masuit.Tools.Reflection
                     return t.CreateInstance(type) as T;
                 }
             }
+
             return null;
             //return Assembly.GetExecutingAssembly().CreateInstance(type);
         }
@@ -399,6 +415,7 @@ namespace Masuit.Tools.Reflection
         {
             return CreateInstance<T>(type.FullName);
         }
+
         #endregion
     }
 }

文件差異過大導致無法顯示
+ 332 - 248
Masuit.Tools.Core/Security/Encrypt.cs


+ 4 - 3
Masuit.Tools.Core/Security/HashEncode.cs

@@ -1,7 +1,7 @@
-using System;
+using Masuit.Tools.Win32;
+using System;
 using System.Security.Cryptography;
 using System.Text;
-using Masuit.Tools.Win32;
 
 namespace Masuit.Tools.Security
 {
@@ -32,7 +32,8 @@ namespace Masuit.Tools.Security
             {
                 sb.Append((int)o + "O");
             }
+
             return sb.ToString();
         }
     }
-}
+}

+ 6 - 1
Masuit.Tools.Core/Security/RSACrypt.cs

@@ -20,6 +20,7 @@ namespace Masuit.Tools.Security
         /// </summary>
         public string PrivateKey;
     }
+
     /// <summary> 
     /// RSA加密解密及RSA签名和验证
     /// </summary> 
@@ -36,7 +37,11 @@ namespace Masuit.Tools.Security
         {
             using (var rsa = new RSACryptoServiceProvider())
             {
-                return new RsaKey { PrivateKey = rsa.ToXmlString(true), PublicKey = rsa.ToXmlString(false) };
+                return new RsaKey
+                {
+                    PrivateKey = rsa.ToXmlString(true),
+                    PublicKey = rsa.ToXmlString(false)
+                };
             }
         }
 

+ 32 - 0
Masuit.Tools.Core/Strings/Template.cs

@@ -0,0 +1,32 @@
+using System;
+using System.Text.RegularExpressions;
+
+namespace Masuit.Tools.Strings
+{
+    public class Template
+    {
+        private string Content { get; set; }
+
+        public Template(string content)
+        {
+            Content = content;
+        }
+
+        public Template Set(string key, string value)
+        {
+            Content = Content.Replace("{{" + key + "}}", value);
+            return this;
+        }
+
+        public string Render()
+        {
+            var mc = Regex.Matches(Content, @"\{\{.+?\}\}");
+            foreach (Match m in mc)
+            {
+                throw new ArgumentException($"模版变量{m.Value}未被使用");
+            }
+            return Content;
+        }
+
+    }
+}

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

@@ -2,7 +2,7 @@
 using System.Collections.Generic;
 using System.Linq;
 
-namespace Masuit.Tools.Core.Systems
+namespace Masuit.Tools.Systems
 {
     /// <summary>
     /// 定长队列

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

@@ -1,6 +1,6 @@
 using System;
 
-namespace Masuit.Tools.Core.Systems
+namespace Masuit.Tools.Systems
 {
     public abstract class Disposable : IDisposable
     {

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

@@ -3,6 +3,7 @@ using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
 using System.Linq;
 using System.Reflection;
 
@@ -31,6 +32,7 @@ namespace Masuit.Tools.Systems
                 names = GetDictionaryItems(enumType);
                 EnumNameValueDict[enumType] = names;
             }
+
             return names;
         }
 
@@ -40,9 +42,10 @@ 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;
             }
+
             return names;
         }
 
@@ -60,6 +63,7 @@ namespace Masuit.Tools.Systems
                 values = GetValueNameItems(enumType);
                 EnumValueNameDict[enumType] = values;
             }
+
             return values;
         }
 
@@ -69,8 +73,9 @@ 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,6 +106,7 @@ namespace Masuit.Tools.Systems
             {
                 return _enumTypeDict[typeName];
             }
+
             return null;
         }
 
@@ -121,8 +127,9 @@ 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;
         }
 
@@ -142,6 +149,27 @@ namespace Masuit.Tools.Systems
                     return attrs[0].Description; //返回当前描述  
                 }
             }
+
+            return en.ToString();
+        }
+
+        /// <summary>
+        /// 根据枚举成员获取Display的属性Name
+        /// </summary>
+        /// <returns></returns>
+        public static string GetDisplay(this Enum en)
+        {
+            Type type = en.GetType(); //获取类型  
+            MemberInfo[] memberInfos = type.GetMember(en.ToString()); //获取成员  
+            if (memberInfos.Any())
+            {
+                DisplayAttribute[] attrs = memberInfos[0]?.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[]; //获取描述特性  
+                if (attrs != null && attrs.Length > 0)
+                {
+                    return attrs[0].Name; //返回当前描述  
+                }
+            }
+
             return en.ToString();
         }
 
@@ -170,11 +198,12 @@ 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);
                 }
             }
+
             return nvc;
         }
     }
-}
+}

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

@@ -1,6 +1,6 @@
 using System.Collections.Generic;
 
-namespace Masuit.Tools.Core.Systems
+namespace Masuit.Tools.Systems
 {
     /// <summary>
     /// 定长队列

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

@@ -1,7 +1,7 @@
 using System;
 using StackExchange.Redis;
 
-namespace Masuit.Tools.Core.Systems
+namespace Masuit.Tools.Systems
 {
     public class Lock
     {

+ 38 - 22
Masuit.Tools.Core/Systems/RedisLock.cs

@@ -5,16 +5,19 @@ using System.Threading.Tasks;
 using System.Timers;
 using StackExchange.Redis;
 
-namespace Masuit.Tools.Core.Systems
+namespace Masuit.Tools.Systems
 {
     public class RedisLock : IDisposable
     {
         #region Property
-        private bool isDisposed;
+
+        private bool _isDisposed;
+
         ~RedisLock()
         {
             Dispose(false);
         }
+
         /// <summary>
         /// KEYS[1] :需要加锁的key,这里需要是字符串类型。
         /// ARGV[1] :锁的超时时间,防止死锁
@@ -76,6 +79,10 @@ namespace Masuit.Tools.Core.Systems
 
         #region Constructor
 
+        /// <summary>
+        /// 默认连接127.0.0.1:6379,synctimeout=20000
+        /// </summary>
+        /// <param name="connstr"></param>
         public RedisLock(string connstr = "127.0.0.1:6379,synctimeout=20000")
         {
             _server = ConnectionMultiplexer.Connect(connstr);
@@ -161,10 +168,23 @@ namespace Masuit.Tools.Core.Systems
         /// <returns></returns>
         public RedisResult UnLock(Lock lockObject)
         {
-            if (lockObject == null) return null;
+            if (lockObject == null)
+            {
+                return null;
+            }
+
             CancelExpirationRenewal(lockObject);
-            RedisKey[] key = { lockObject.Resource, GetChannelName(lockObject.Resource) };
-            RedisValue[] values = { Thread.CurrentThread.ManagedThreadId, 10000, lockObject.Value };
+            RedisKey[] key =
+            {
+                lockObject.Resource,
+                GetChannelName(lockObject.Resource)
+            };
+            RedisValue[] values =
+            {
+                Thread.CurrentThread.ManagedThreadId,
+                10000,
+                lockObject.Value
+            };
             return _server.GetDatabase().ScriptEvaluate(UnLockScript, key, values);
         }
 
@@ -207,8 +227,15 @@ namespace Masuit.Tools.Core.Systems
 
         private RedisResult LockInnerAsync(RedisKey resource, TimeSpan waitTime, string threadId)
         {
-            RedisKey[] key = { resource };
-            RedisValue[] values = { waitTime.TotalMilliseconds, threadId };
+            RedisKey[] key =
+            {
+                resource
+            };
+            RedisValue[] values =
+            {
+                waitTime.TotalMilliseconds,
+                threadId
+            };
             return _server.GetDatabase().ScriptEvaluate(LockScript, key, values);
         }
 
@@ -236,21 +263,9 @@ namespace Masuit.Tools.Core.Systems
         protected CancellationTokenSource TaskTimeOut(Func<Lock, bool> action, Lock lockObj, int time)
         {
             var timeoutCancellationTokenSource = new CancellationTokenSource();
-            var task = Task.Run(() =>
+            Task.Run(() =>
             {
                 SpinWait.SpinUntil(() => !timeoutCancellationTokenSource.IsCancellationRequested);
-                if (action(lockObj))
-                {
-                    //Console.WriteLine("锁:" + lockObj.Value + " 重置过期时间");
-                }
-                //while (!timeoutCancellationTokenSource.IsCancellationRequested)
-                //{
-                //    Thread.Sleep(time);
-                //    if (action(lockObj))
-                //    {
-                //        Console.WriteLine("锁:" + lockObj.Value + " 重置过期时间");
-                //    }
-                //}
             }, timeoutCancellationTokenSource.Token);
             return timeoutCancellationTokenSource;
         }
@@ -297,12 +312,13 @@ namespace Masuit.Tools.Core.Systems
 
         public virtual void Dispose(bool disposing)
         {
-            if (isDisposed)
+            if (_isDisposed)
             {
                 return;
             }
+
             _server?.Dispose();
-            isDisposed = true;
+            _isDisposed = true;
             //_server = null;
         }
     }

+ 3 - 1
Masuit.Tools/Database/DataExt.cs

@@ -1,7 +1,6 @@
 using System;
 using System.Data;
 using System.Data.SqlClient;
-using System.IO;
 using System.Reflection;
 
 namespace Masuit.Tools.Database
@@ -26,6 +25,7 @@ namespace Masuit.Tools.Database
             {
                 p.SetValue(obj, reader[p.Name]);
             }
+
             return obj;
         }
 
@@ -44,6 +44,7 @@ namespace Masuit.Tools.Database
             {
                 p.SetValue(obj, row[p.Name]);
             }
+
             return obj;
         }
 
@@ -62,6 +63,7 @@ namespace Masuit.Tools.Database
             {
                 p.SetValue(obj, dr[p.Name]);
             }
+
             return obj;
         }
     }

+ 62 - 35
Masuit.Tools/Database/DataTableHelper.cs

@@ -28,6 +28,7 @@ namespace Masuit.Tools.Database
                     dt.Rows[i]["identityid"] = (i + 1).ToString();
                 }
             }
+
             return dt;
         }
 
@@ -36,12 +37,9 @@ namespace Masuit.Tools.Database
         /// </summary>
         /// <param name="dt">DataTable</param>
         /// <returns>是否有数据行</returns>
-        public static bool IsHaveRows(this DataTable dt)
+        public static bool HasRows(this DataTable dt)
         {
-            if (dt?.Rows.Count > 0)
-                return true;
-
-            return false;
+            return dt.Rows.Count > 0;
         }
 
         /// <summary>
@@ -52,8 +50,10 @@ namespace Masuit.Tools.Database
         /// <returns>强类型的数据集合</returns>
         public static IList<T> DataTableToList<T>(this DataTable table) where T : class
         {
-            if (!IsHaveRows(table))
+            if (!HasRows(table))
+            {
                 return new List<T>();
+            }
 
             IList<T> list = new List<T>();
             foreach (DataRow dr in table.Rows)
@@ -70,8 +70,10 @@ namespace Masuit.Tools.Database
                         pi.SetValue(model, drValue, null);
                     }
                 }
+
                 list.Add(model);
             }
+
             return list;
         }
 
@@ -88,6 +90,7 @@ namespace Masuit.Tools.Database
             {
                 return null;
             }
+
             var dt = new DataTable(typeof(T).Name);
             PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
             int length = myPropertyInfo.Length;
@@ -98,6 +101,7 @@ namespace Masuit.Tools.Database
                 {
                     continue;
                 }
+
                 var row = dt.NewRow();
                 for (int i = 0; i < length; i++)
                 {
@@ -108,14 +112,18 @@ namespace Masuit.Tools.Database
                         var column = new DataColumn(name, pi.PropertyType);
                         dt.Columns.Add(column);
                     }
+
                     row[name] = pi.GetValue(t, null);
                 }
+
                 if (createColumn)
                 {
                     createColumn = false;
                 }
+
                 dt.Rows.Add(row);
             }
+
             return dt;
         }
 
@@ -127,7 +135,7 @@ namespace Masuit.Tools.Database
         /// <returns>数据集(表)</returns>
         public static DataTable ToDataTable<T>(this IList<T> list)
         {
-            return ToDataTable<T>(list, null);
+            return ToDataTable(list, null);
         }
 
         /// <summary>
@@ -141,48 +149,55 @@ namespace Masuit.Tools.Database
         {
             List<string> propertyNameList = new List<string>();
             if (propertyName != null)
+            {
                 propertyNameList.AddRange(propertyName);
+            }
+
             DataTable result = new DataTable();
-            if (list.Count > 0)
+            if (list.Count <= 0)
+            {
+                return result;
+            }
+
+            PropertyInfo[] propertys = list[0].GetType().GetProperties();
+            propertys.ForEach(pi =>
             {
-                PropertyInfo[] propertys = list[0].GetType().GetProperties();
-                propertys.ForEach(pi =>
+                if (propertyNameList.Count == 0)
                 {
-                    if (propertyNameList.Count == 0)
+                    result.Columns.Add(pi.Name, pi.PropertyType);
+                }
+                else
+                {
+                    if (propertyNameList.Contains(pi.Name))
                     {
                         result.Columns.Add(pi.Name, pi.PropertyType);
                     }
-                    else
+                }
+            });
+            list.ForEach(item =>
+            {
+                ArrayList tempList = new ArrayList();
+                foreach (PropertyInfo pi in propertys)
+                {
+                    if (propertyNameList.Count == 0)
                     {
-                        if (propertyNameList.Contains(pi.Name))
-                        {
-                            result.Columns.Add(pi.Name, pi.PropertyType);
-                        }
+                        object obj = pi.GetValue(item, null);
+                        tempList.Add(obj);
                     }
-                });
-                list.ForEach(item =>
-                {
-                    ArrayList tempList = new ArrayList();
-                    foreach (PropertyInfo pi in propertys)
+                    else
                     {
-                        if (propertyNameList.Count == 0)
+                        if (propertyNameList.Contains(pi.Name))
                         {
                             object obj = pi.GetValue(item, null);
                             tempList.Add(obj);
                         }
-                        else
-                        {
-                            if (propertyNameList.Contains(pi.Name))
-                            {
-                                object obj = pi.GetValue(item, null);
-                                tempList.Add(obj);
-                            }
-                        }
                     }
-                    object[] array = tempList.ToArray();
-                    result.LoadDataRow(array, true);
-                });
-            }
+                }
+
+                object[] array = tempList.ToArray();
+                result.LoadDataRow(array, true);
+            });
+
             return result;
         }
 
@@ -194,12 +209,16 @@ namespace Masuit.Tools.Database
         public static DataTable CreateTable(this List<string> nameList)
         {
             if (nameList.Count <= 0)
+            {
                 return null;
+            }
+
             var myDataTable = new DataTable();
             foreach (string columnName in nameList)
             {
                 myDataTable.Columns.Add(columnName, typeof(string));
             }
+
             return myDataTable;
         }
 
@@ -229,6 +248,7 @@ namespace Masuit.Tools.Database
                     }
                 }
             }
+
             return dt;
         }
 
@@ -298,6 +318,7 @@ namespace Masuit.Tools.Database
                     newType = typeof(char);
                     break;
             }
+
             return newType;
         }
 
@@ -314,6 +335,7 @@ namespace Masuit.Tools.Database
             {
                 drs[i] = drc[i];
             }
+
             return drs;
         }
 
@@ -329,12 +351,14 @@ namespace Masuit.Tools.Database
             {
                 return new DataTable();
             }
+
             DataTable dt = rows[0].Table.Clone();
             dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
             for (int i = 0; i < rows.Length; i++)
             {
                 dt.LoadDataRow(rows[i].ItemArray, true);
             }
+
             return dt;
         }
 
@@ -353,8 +377,10 @@ namespace Masuit.Tools.Database
                 {
                     tmp += sorts[i] + ",";
                 }
+
                 dt.DefaultView.Sort = tmp.TrimEnd(',');
             }
+
             return dt;
         }
 
@@ -370,10 +396,11 @@ namespace Masuit.Tools.Database
             {
                 return dt;
             }
+
             var newdt = dt.Clone();
             DataRow[] dr = dt.Select(condition);
             dr.ForEach(t => newdt.ImportRow(t));
             return newdt;
         }
     }
-}
+}

+ 0 - 972
Masuit.Tools/DateTimeExt/CNCalendar.cs

@@ -1,972 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-using System.Xml;
-
-namespace Masuit.Tools.DateTimeExt
-{
-    /// <summary>
-    /// 日历操作
-    /// </summary>
-    public static class CNCalendar
-    {
-        /// <summary>
-        /// 格式化日期
-        /// </summary>
-        /// <param name="m">月份</param>
-        /// <param name="d">日期</param>
-        /// <returns>x月x日</returns>
-        private static string FormatDate(int m, int d)
-        {
-            return $"{m:00}{d:00}";
-        }
-
-        /// <summary>
-        /// 从嵌入资源中读取文件内容(e.g: xml).
-        /// </summary>
-        /// <param name="fileWholeName">嵌入资源文件名,包括项目的命名空间.</param>
-        /// <returns>资源中的文件内容.</returns>
-        public static string ReadFileFromEmbedded(string fileWholeName)
-        {
-            //文件属性-生成操作-嵌入的资源
-            using (TextReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(fileWholeName)))
-            {
-                return reader.ReadToEnd();
-            }
-        }
-
-        #region 结构、日期对象
-
-        /// <summary>
-        /// 结构、日期对象
-        /// </summary>
-        private struct structDate
-        {
-            public int year;
-            public int month;
-            public int day;
-            public bool isLeap; //是否闰月
-            public int yearCyl; //年干支
-            public int monthCyl; //月干支
-            public int dayCyl; //日干支
-        }
-
-        #endregion
-
-        #region 结构、完整的日期对象
-
-        /// <summary>
-        /// 结构、完整的日期对象
-        /// </summary>
-        public struct StructDateFullInfo
-        {
-            /// <summary>
-            /// 公历年
-            /// </summary>
-            public int Year;
-
-            /// <summary>
-            /// 公历月
-            /// </summary>
-            public int Month;
-
-            /// <summary>
-            /// 公历日
-            /// </summary>
-            public int Day;
-
-            /// <summary>
-            /// 是否闰月
-            /// </summary>
-            public bool IsLeap; //是否闰月
-
-            /// <summary>
-            /// 农历年
-            /// </summary>
-            public int Cyear; //农历年
-
-            /// <summary>
-            /// 农历年名称
-            /// </summary>
-            public string Scyear; //农历年名称
-
-            /// <summary>
-            /// 干支年
-            /// </summary>
-            public string CyearCyl; //干支年
-
-            /// <summary>
-            /// 农历月
-            /// </summary>
-            public int Cmonth; //农历月
-
-            /// <summary>
-            /// 农历月名称
-            /// </summary>
-            public string Scmonth; //农历月名称
-
-            /// <summary>
-            /// 干支月
-            /// </summary>
-            public string CmonthCyl; //干支月
-
-            /// <summary>
-            /// 农历日
-            /// </summary>
-            public int Cday; //农历日
-
-            /// <summary>
-            /// 农历日名称
-            /// </summary>
-            public string Scday; //农历日名称
-
-            /// <summary>
-            /// 干支日
-            /// </summary>
-            public string CdayCyl; //干支日
-
-            /// <summary>
-            /// 农历属象
-            /// </summary>
-            public string cnAnm;
-
-            /// <summary>
-            /// 节气
-            /// </summary>
-            public string solarterm; //节气
-
-            /// <summary>
-            /// 星期几
-            /// </summary>
-            public string DayInWeek; //星期几
-
-            /// <summary>
-            /// 节日
-            /// </summary>
-            public string Feast; //节日
-
-            /// <summary>
-            /// 完整的日期信息
-            /// </summary>
-            public string Fullinfo; //完整的日期信息
-
-            /// <summary>
-            /// 阴历节日
-            /// </summary>
-            public string cnFtvl;
-
-            /// <summary>
-            /// 阳历节日
-            /// </summary>
-            public string cnFtvs;
-
-            /// <summary>
-            /// 系统问候语
-            /// </summary>
-            public string Info; //系统问候语
-
-            /// <summary>
-            /// 主题图片
-            /// </summary>
-            public string Image; //主题图片
-
-            /// <summary>
-            /// 有特别的问候语吗
-            /// </summary>
-            public bool SayHello; //有特别的问候语吗?
-        }
-
-        #endregion
-
-        #region 私有
-
-        #region  农历月份信息
-
-        /// <summary>
-        /// 农历月份信息
-        /// </summary>
-        private static readonly int[] lunarInfo =
-        {
-            0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
-            0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
-            0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
-            0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
-            0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
-            0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,
-            0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
-            0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
-            0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
-            0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
-            0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
-            0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
-            0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
-            0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
-            0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0
-        };
-
-        #endregion
-
-        /// <summary>
-        /// 农历月份名字
-        /// </summary>
-        private static readonly string[] cMonthName = { "", "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
-
-        //农历日子
-        private static readonly string[] nStr1 = { "日", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
-        private static readonly string[] nStr2 = { "初", "十", "廿", "卅", " " };
-        //公历月份名称
-        private static string[] monthName = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
-
-        /// <summary>
-        /// 天干
-        /// </summary>
-        private static readonly string[] gan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
-
-        /// <summary>
-        /// 地支
-        /// </summary>
-        private static readonly string[] zhi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
-
-        /// <summary>
-        /// 生肖
-        /// </summary>
-        private static readonly string[] animals
-            =
-            {
-                "鼠", "牛", "虎", "兔",
-                "龙", "蛇", "马", "羊",
-                "猴", "鸡", "狗", "猪"
-            };
-
-        /// <summary>
-        /// 节气
-        /// </summary>
-        private static readonly string[] solarTerm
-            =
-            {
-                "小寒", "大寒", "立春", "雨水",
-                "惊蛰", "春分", "清明", "谷雨",
-                "立夏", "小满", "芒种", "夏至",
-                "小暑", "大暑", "立秋", "处暑",
-                "白露", "秋分", "寒露", "霜降",
-                "立冬", "小雪", "大雪", "冬至"
-            };
-
-        /// <summary>
-        /// 节气对应数值?
-        /// </summary>
-        private static readonly int[] solarTermInfo =
-        {
-            0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072
-            , 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795
-            , 462224, 483532, 504758
-        };
-
-        #region 节日信息
-
-        private static readonly string[] lFtv = { "0101农历春节", "0202 龙抬头节", "0115 元宵节", "0505 端午节", "0707 七夕情人节", "0815 中秋节", "0909 重阳节", "1208 腊八节", "1114 李君先生生日", "1224 小年", "0100除夕" };
-        /// <summary>
-        /// 节假日信息
-        /// </summary>
-        private static readonly string[] sFtv =
-        {
-            "0101 新年元旦",
-            "0202 世界湿地日",
-            "0207 国际声援南非日",
-            "0210 国际气象节",
-            "0214 情人节",
-            "0301 国际海豹日",
-            "0303 全国爱耳日",
-            "0308 国际妇女节",
-            "0312 植树节 孙中山逝世纪念日",
-            "0314 国际警察日",
-            "0315 国际消费者权益日",
-            "0317 中国国医节 国际航海日",
-            "0321 世界森林日 消除种族歧视国际日",
-            "0321 世界儿歌日",
-            "0322 世界水日",
-            "0323 世界气象日",
-            "0324 世界防治结核病日",
-            "0325 全国中小学生安全教育日",
-            "0330 巴勒斯坦国土日",
-            "0401 愚人节 全国爱国卫生运动月(四月) 税收宣传月(四月)",
-            "0407 世界卫生日",
-            "0422 世界地球日",
-            "0423 世界图书和版权日",
-            "0424 亚非新闻工作者日",
-            "0501 国际劳动节",
-            "0504 中国五四青年节",
-            "0505 碘缺乏病防治日",
-            "0508 世界红十字日",
-            "0512 国际护士节",
-            "0515 国际家庭日",
-            "0517 世界电信日",
-            "0518 国际博物馆日",
-            "0520 全国学生营养日",
-            "0523 国际牛奶日",
-            "0531 世界无烟日",
-            "0601 国际儿童节",
-            "0605 世界环境日",
-            "0606 全国爱眼日",
-            "0617 防治荒漠化和干旱日",
-            "0623 国际奥林匹克日",
-            "0625 全国土地日",
-            "0626 国际反毒品日",
-            "0701 中国共产党建党日 世界建筑日",
-            "0702 国际体育记者日",
-            "0707 中国人民抗日战争纪念日",
-            "0711 世界人口日",
-            "0730 非洲妇女日",
-            "0801 中国建军节",
-            "0808 中国男子节(爸爸节)",
-            "0815 日本正式宣布无条件投降日",
-            "0908 国际扫盲日 国际新闻工作者日",
-            "0910 教师节",
-            "0914 世界清洁地球日",
-            "0916 国际臭氧层保护日",
-            "0918 九·一八事变纪念日",
-            "0920 全国爱牙日",
-            "0927 世界旅游日",
-            "1001 国庆节 世界音乐日 国际老人节",
-            "1001 国际音乐日",
-            "1002 国际和平与民主自由斗争日",
-            "1004 世界动物日",
-            "1008 全国高血压日",
-            "1008 世界视觉日",
-            "1009 世界邮政日 万国邮联日",
-            "1010 辛亥革命纪念日 世界精神卫生日",
-            "1013 世界保健日 国际教师节",
-            "1014 世界标准日",
-            "1015 国际盲人节(白手杖节)",
-            "1016 世界粮食日",
-            "1017 世界消除贫困日",
-            "1022 世界传统医药日",
-            "1024 联合国日 世界发展信息日",
-            "1031 世界勤俭日",
-            "1107 十月社会主义革命纪念日",
-            "1108 中国记者日",
-            "1109 全国消防安全宣传教育日",
-            "1110 世界青年节",
-            "1111 国际科学与和平周(本日所属的一周)",
-            "1112 孙中山诞辰纪念日",
-            "1114 世界糖尿病日",
-            "1117 国际大学生节 世界学生节",
-            "1121 世界问候日 世界电视日",
-            "1129 国际声援巴勒斯坦人民国际日",
-            "1201 世界艾滋病日",
-            "1203 世界残疾人日",
-            "1205 国际经济和社会发展志愿人员日",
-            "1208 国际儿童电视日",
-            "1209 世界足球日",
-            "1210 世界人权日",
-            "1212 西安事变纪念日",
-            "1213 南京大屠杀(1937年)纪念日!紧记血泪史!",
-            "1221 国际篮球日",
-            "1224 平安夜",
-            "1225 圣诞节",
-            "1226 毛主席诞辰",
-            "1229 国际生物多样性日"
-        };
-
-        #endregion
-
-        #endregion
-
-        #region 私有方法
-
-        /// <summary>
-        /// 传回农历y年的总天数
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static int GetLYearDays(int y)
-        {
-            int sum = 348;
-
-            for (int i = 0x8000; i > 0x8; i >>= 1)
-                sum += (lunarInfo[y - 1900] & i) > 0 ? 1 : 0;
-
-            return sum + GetLeapDays(y);
-        }
-
-        /// <summary>
-        /// 传回农历y年闰月的天数
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static int GetLeapDays(int y)
-        {
-            if (GetLeapMonth(y) > 0)
-                return (lunarInfo[y - 1900] & 0x10000) > 0 ? 30 : 29;
-            return 0;
-        }
-
-        /// <summary>
-        /// 传回农历y年闰哪个月 1-12 , 没闰传回 0
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static int GetLeapMonth(int y)
-        {
-            return lunarInfo[y - 1900] & 0xf;
-        }
-
-        /// <summary>
-        /// 传回农历y年m月的总天数
-        /// </summary>
-        /// <param name="y">公元年</param>
-        /// <param name="m">月份</param> 
-        private static int GetLMonthDays(int y, int m)
-        {
-            return (lunarInfo[y - 1900] & (0x10000 >> m)) > 0 ? 30 : 29;
-        }
-
-        /// <summary>
-        /// 传回农历y年的生肖
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static string AnimalsYear(int y)
-        {
-            return animals[(y - 4) % 12];
-        }
-
-        /// <summary>
-        ///传入月日的offset 传回天干地支, 0=甲子
-        /// </summary>
-        /// <param name="num">月日的偏差</param>
-        private static string Cyclical(int num)
-        {
-            return gan[num % 10] + zhi[num % 12];
-        }
-
-        /// <summary>
-        /// 传入offset 传回干支, 0=甲子
-        /// </summary>
-        /// <param name="y">公元年</param>
-        private static string cyclical(int y)
-        {
-            int num = y - 1900 + 36;
-            return Cyclical(num);
-        }
-
-        #region 得到农历日期、年月日的天干地址及是否闰月
-
-        #region  返回一个农历日期结构体
-
-        /// <summary>
-        /// 返回一个农历日期结构体
-        /// </summary>
-        /// <param name="date">日期对象</param>
-        /// <returns>农历日期结构体</returns>
-        private static structDate GetLunar(DateTime date)
-        {
-            structDate sd;
-
-            int i = 0, leap = 0, temp = 0;
-            DateTime baseDate = new DateTime(1900, 1, 31); //基准时间
-
-            int offset = (date - baseDate).Days; //与基准时间相隔天数
-
-            sd.dayCyl = offset + 40;
-            sd.monthCyl = 14;
-
-            for (i = 1900; (i < 2050) && (offset > 0); i++)
-            {
-                temp = GetLYearDays(i);
-                offset -= temp;
-                sd.monthCyl += 12;
-            }
-            if (offset < 0)
-            {
-                offset += temp;
-                i--;
-                sd.monthCyl -= 12;
-            }
-
-            sd.year = i;
-            sd.yearCyl = i - 1864;
-
-            //闰哪个月
-            leap = GetLeapMonth(i);
-            sd.isLeap = false;
-            for (i = 1; (i < 13) && (offset > 0); i++)
-            {
-                //闰月 
-                if ((leap > 0) && (i == leap + 1) && (!sd.isLeap))
-                {
-                    --i;
-                    sd.isLeap = true;
-                    temp = GetLeapDays(sd.year);
-                }
-                else
-                {
-                    temp = GetLMonthDays(sd.year, i);
-                }
-                //解除闰月 
-                if (sd.isLeap && (i == leap + 1))
-                    sd.isLeap = false;
-                offset -= temp;
-                if (!sd.isLeap)
-                    sd.monthCyl++;
-            }
-            if ((offset == 0) && (leap > 0) && (i == leap + 1))
-            {
-                if (sd.isLeap)
-                {
-                    sd.isLeap = false;
-                }
-                else
-                {
-                    sd.isLeap = true;
-                    --i;
-                    --sd.monthCyl;
-                }
-            }
-
-            if (offset < 0)
-            {
-                offset += temp;
-                --i;
-                --sd.monthCyl;
-            }
-
-            sd.month = i;
-            sd.day = offset + 1;
-
-            return sd;
-        }
-
-        #endregion
-
-        #region 传出y年m月d日对应的农历 [0].year [1].month [2].day2 [3].yearCyl [4].monCyl [5].dayCyl [6].isLeap
-
-        /// <summary>
-        /// 传出y年m月d日对应的农历[0].year [1].month [2].day2 [3].yearCyl [4].monCyl [5].dayCyl [6].isLeap
-        /// </summary>
-        /// <param name="y">年</param>
-        /// <param name="m">月</param>
-        /// <param name="d">日</param>
-        private static long[] calElement(int y, int m, int d)
-        {
-            long[] nongDate = new long[7];
-
-            int i = 0, temp = 0, leap = 0;
-            DateTime baseDate = new DateTime(1900, 1, 31);
-
-            DateTime objDate = new DateTime(y, m, d);
-            TimeSpan ts = objDate - baseDate;
-
-            long offset = (long)ts.TotalDays;
-            nongDate[5] = offset + 40;
-            nongDate[4] = 14;
-
-            for (i = 1900; (i < 2050) && (offset > 0); i++)
-            {
-                temp = GetLYearDays(i);
-                offset -= temp;
-                nongDate[4] += 12;
-            }
-            if (offset < 0)
-            {
-                offset += temp;
-                i--;
-                nongDate[4] -= 12;
-            }
-            nongDate[0] = i;
-            nongDate[3] = i - 1864;
-            leap = GetLeapMonth(i); // 闰哪个月
-            nongDate[6] = 0;
-
-            for (i = 1; (i < 13) && (offset > 0); i++)
-            {
-                // 闰月
-                if ((leap > 0) && (i == leap + 1) && (nongDate[6] == 0))
-                {
-                    --i;
-                    nongDate[6] = 1;
-                    temp = GetLeapDays((int)nongDate[0]);
-                }
-                else
-                {
-                    temp = GetLMonthDays((int)nongDate[0], i);
-                }
-
-                // 解除闰月
-                if ((nongDate[6] == 1) && (i == leap + 1))
-                    nongDate[6] = 0;
-                offset -= temp;
-                if (nongDate[6] == 0)
-                    nongDate[4]++;
-            }
-
-            if ((offset == 0) && (leap > 0) && (i == leap + 1))
-            {
-                if (nongDate[6] == 1)
-                {
-                    nongDate[6] = 0;
-                }
-                else
-                {
-                    nongDate[6] = 1;
-                    --i;
-                    --nongDate[4];
-                }
-            }
-
-            if (offset < 0)
-            {
-                offset += temp;
-                --i;
-                --nongDate[4];
-            }
-            nongDate[1] = i;
-            nongDate[2] = offset + 1;
-            return nongDate;
-        }
-
-        #endregion
-
-        #endregion
-
-        /// <summary>
-        /// 将值转成农历汉字日子
-        /// </summary>
-        /// <param name="d">农历日</param>
-        /// <returns>中文表示</returns>
-        private static string GetCDay(int d)
-        {
-            string s = "";
-
-            switch (d)
-            {
-                case 10:
-                    s = "初十";
-                    break;
-                case 20:
-                    s = "二十";
-                    break;
-                case 30:
-                    s = "三十";
-                    break;
-                default:
-                    s = nStr2[(int)Math.Floor((double)d / 10)];
-                    s += nStr1[d % 10];
-                    break;
-            }
-            return s;
-        }
-
-        /// <summary>
-        ///  某年的第n个节气为几日(从0,即小寒起算)
-        ///	n:节气下标
-        /// </summary>
-        /// <param name="y">年</param>
-        /// <param name="n">节气</param>
-        /// <returns>日期时间</returns>
-        private static DateTime GetSolarTermDay(int y, int n)
-        {
-            //按分钟起计算
-            double minutes = (525948.766245 * (y - 1900)) + solarTermInfo[n - 1];
-            //1900年1月6日:小寒 
-            DateTime baseDate = new DateTime(1900, 1, 6, 2, 5, 0);
-            DateTime veryDate = baseDate.AddMinutes(minutes);
-            return veryDate;
-            //按毫秒起计算
-            //double ms = 31556925974.7 * (y - 1900);
-            // double ms1 = solarTermInfo[n];
-            // DateTime baseDate = new DateTime(1900, 1, 6, 2, 5, 0);
-            // baseDate = baseDate.AddMilliseconds(ms);
-            // baseDate = baseDate.AddMinutes(ms1);
-        }
-
-        #endregion
-
-        #region 公有方法
-
-        #region 得到精简日期信息(不含节日)
-
-        /// <summary>
-        /// 得到精简日期信息(不含节日)
-        /// </summary>
-        /// <param name="d">待检查的日子</param>
-        /// <returns>日期信息</returns>
-        public static StructDateFullInfo GetDateTidyInfo(this DateTime d)
-        {
-            var dayinfo = new StructDateFullInfo();
-            structDate day = GetLunar(d);
-            dayinfo.IsLeap = day.isLeap;
-            dayinfo.Year = d.Year;
-            dayinfo.Cyear = day.year;
-            dayinfo.Scyear = animals[(day.year - 4) % 12];
-            dayinfo.CyearCyl = Cyclical(day.yearCyl); //干支年
-            dayinfo.Month = d.Month;
-            dayinfo.Cmonth = day.month;
-            dayinfo.Scmonth = cMonthName[day.month];
-            dayinfo.CmonthCyl = Cyclical(day.monthCyl); //干支月
-            dayinfo.Day = d.Day;
-            dayinfo.Cday = day.day;
-            dayinfo.Scday = GetCDay(day.day); //日子
-            dayinfo.CdayCyl = Cyclical(day.dayCyl); //干支日
-            switch (d.DayOfWeek)
-            {
-                case DayOfWeek.Sunday:
-                    dayinfo.DayInWeek = "星期日";
-                    break;
-                case DayOfWeek.Monday:
-                    dayinfo.DayInWeek = "星期一";
-                    break;
-                case DayOfWeek.Tuesday:
-                    dayinfo.DayInWeek = "星期二";
-                    break;
-                case DayOfWeek.Wednesday:
-                    dayinfo.DayInWeek = "星期三";
-                    break;
-                case DayOfWeek.Thursday:
-                    dayinfo.DayInWeek = "星期四";
-                    break;
-                case DayOfWeek.Friday:
-                    dayinfo.DayInWeek = "星期五";
-                    break;
-                case DayOfWeek.Saturday:
-                    dayinfo.DayInWeek = "星期六";
-                    break;
-                default:
-                    dayinfo.DayInWeek = "星期?";
-                    break;
-            }
-
-            dayinfo.Info = "";
-            dayinfo.Feast = "";
-            dayinfo.Image = "";
-            dayinfo.SayHello = false;
-
-            //节气
-            //每个月有两个节气
-            int d1 = GetSolarTermDay(d.Year, (d.Month * 2) - 1).Day;
-            int d2 = GetSolarTermDay(d.Year, d.Month * 2).Day;
-            if (dayinfo.Day == d1)
-            {
-                if (solarTerm.Length > d.Month * 2 - 2) dayinfo.solarterm = solarTerm[d.Month * 2 - 2];
-            }
-            else if (dayinfo.Day == d2)
-            {
-                dayinfo.solarterm = solarTerm[d.Month * 2 - 1];
-            }
-            else
-            {
-                dayinfo.solarterm = "";
-            }
-
-            dayinfo.Fullinfo = dayinfo.Year + "年" + dayinfo.Month + "月" + dayinfo.Day + "日";
-            dayinfo.Fullinfo += " " + dayinfo.DayInWeek;
-            dayinfo.Fullinfo += " 农历" + dayinfo.CyearCyl + "(" + dayinfo.Scyear + ")年";
-            if (dayinfo.IsLeap)
-                dayinfo.Fullinfo += "闰";
-            dayinfo.Fullinfo += dayinfo.Scmonth + dayinfo.Scday;
-            if (dayinfo.solarterm != "")
-                dayinfo.Fullinfo += " " + dayinfo.solarterm;
-
-            return dayinfo;
-        }
-
-        #endregion
-
-        #region    得到日期信息
-
-        /// <summary>
-        /// 得到日期信息
-        /// </summary>
-        /// <param name="d">待检查的日子</param>
-        /// <returns>日期信息</returns>
-        public static StructDateFullInfo GetDateInfo(this DateTime d)
-        {
-            // xml文件属性-生成操作-嵌入的资源
-            string calendarXmlData = ReadFileFromEmbedded("Core.Common" + "CCalendarData.xml");
-
-            StructDateFullInfo dayinfo = new StructDateFullInfo();
-            structDate day = GetLunar(d);
-
-            dayinfo.IsLeap = day.isLeap;
-
-            dayinfo.Year = d.Year;
-            dayinfo.Cyear = day.year;
-            dayinfo.Scyear = animals[(day.year - 4) % 12];
-            dayinfo.CyearCyl = Cyclical(day.yearCyl); //干支年
-
-            dayinfo.Month = d.Month;
-            dayinfo.Cmonth = day.month;
-            dayinfo.Scmonth = cMonthName[day.month];
-            dayinfo.CmonthCyl = Cyclical(day.monthCyl); //干支月
-
-            dayinfo.Day = d.Day;
-            dayinfo.Cday = day.day;
-            dayinfo.Scday = GetCDay(day.day); //日子
-            dayinfo.CdayCyl = Cyclical(day.dayCyl); //干支日
-
-            switch (d.DayOfWeek)
-            {
-                case DayOfWeek.Sunday:
-                    dayinfo.DayInWeek = "星期日";
-                    break;
-                case DayOfWeek.Monday:
-                    dayinfo.DayInWeek = "星期一";
-                    break;
-                case DayOfWeek.Tuesday:
-                    dayinfo.DayInWeek = "星期二";
-                    break;
-                case DayOfWeek.Wednesday:
-                    dayinfo.DayInWeek = "星期三";
-                    break;
-                case DayOfWeek.Thursday:
-                    dayinfo.DayInWeek = "星期四";
-                    break;
-                case DayOfWeek.Friday:
-                    dayinfo.DayInWeek = "星期五";
-                    break;
-                case DayOfWeek.Saturday:
-                    dayinfo.DayInWeek = "星期六";
-                    break;
-                default:
-                    dayinfo.DayInWeek = "星期?";
-                    break;
-            }
-
-            //节气
-            //每个月有两个节气
-            int d1 = GetSolarTermDay(d.Year, d.Month * 2 - 1).Day;
-            int d2 = GetSolarTermDay(d.Year, d.Month * 2).Day;
-            if (dayinfo.Day == d1)
-                dayinfo.solarterm = solarTerm[d.Month * 2 - 2];
-            else if (dayinfo.Day == d2)
-                dayinfo.solarterm = solarTerm[d.Month * 2 - 1];
-            else
-                dayinfo.solarterm = "";
-
-            //节日及问候语
-            dayinfo.Info = "";
-            dayinfo.Feast = "";
-            dayinfo.Image = "";
-            dayinfo.SayHello = false;
-            XmlDocument feastdoc = new XmlDocument();
-            feastdoc.LoadXml(calendarXmlData);
-
-            //公历
-            XmlNodeList nodeList = feastdoc.SelectNodes("descendant::AD/feast[@day='" + d.ToString("MMdd") + "']");
-            foreach (XmlNode root in nodeList)
-            {
-                dayinfo.Feast += root.Attributes["name"].InnerText + " ";
-                if (root.Attributes["sayhello"].InnerText == "yes")
-                {
-                    //需要显示节日问候语
-                    dayinfo.Info = root["hello"].InnerText;
-                    //看看是否需要计算周年
-                    if (root["startyear"] != null)
-                    {
-                        int startyear = Convert.ToInt32(root["startyear"].InnerText);
-                        dayinfo.Info = dayinfo.Info.Replace("_YEARS_", (d.Year - startyear).ToString());
-                    }
-                    dayinfo.Image = root["img"].InnerText;
-                    dayinfo.SayHello = true;
-                }
-            }
-
-            //农历
-            string smmdd = "";
-            smmdd = dayinfo.Cmonth.ToString().Length == 2 ? dayinfo.Cmonth.ToString() : "0" + dayinfo.Cmonth;
-            smmdd += dayinfo.Cday.ToString().Length == 2 ? dayinfo.Cday.ToString() : "0" + dayinfo.Cday;
-            XmlNode feast = feastdoc.SelectSingleNode("descendant::LUNAR/feast[@day='" + smmdd + "']");
-            if (feast != null)
-            {
-                dayinfo.Feast += feast.Attributes["name"].InnerText;
-
-                if (feast.Attributes["sayhello"].InnerText == "yes")
-                {
-                    //需要显示节日问候语
-                    dayinfo.Info += feast["hello"].InnerText;
-                    dayinfo.Image = feast["img"].InnerText;
-                    dayinfo.SayHello = true;
-                }
-            }
-            //普通日子或没有庆贺语
-            if (dayinfo.Info?.Length == 0)
-            {
-                feast = feastdoc.SelectSingleNode("descendant::NORMAL/day[@time1<'" + d.ToString("HHmm") + "']");
-                if (feast != null)
-                {
-                    dayinfo.Info = feast["hello"].InnerText;
-                    dayinfo.Image = feast["img"].InnerText;
-                }
-            }
-
-            dayinfo.Fullinfo = dayinfo.Year + "年" + dayinfo.Month + "月" + dayinfo.Day + "日";
-            dayinfo.Fullinfo += dayinfo.DayInWeek;
-            dayinfo.Fullinfo += " 农历" + dayinfo.CyearCyl + "[" + dayinfo.Scyear + "]年";
-            if (dayinfo.IsLeap)
-                dayinfo.Fullinfo += "闰";
-            dayinfo.Fullinfo += dayinfo.Scmonth + dayinfo.Scday;
-            if (dayinfo.solarterm != "")
-                dayinfo.Fullinfo += "  " + dayinfo.solarterm;
-
-            return dayinfo;
-        }
-
-        #endregion
-
-        /// <summary>
-        /// 获取农历
-        /// </summary>
-        /// <param name="dt">阳历日期</param>
-        public static StructDateFullInfo getChinaDate(this DateTime dt)
-        {
-            StructDateFullInfo cd = new StructDateFullInfo();
-            int year = dt.Year;
-            int month = dt.Month;
-            int date = dt.Day;
-            long[] l = calElement(year, month, date);
-            cd.Cyear = (int)l[0];
-            cd.Cmonth = (int)l[1];
-            cd.Cday = (int)l[2];
-            cd.Scyear = cyclical(year);
-            cd.cnAnm = AnimalsYear(year);
-            cd.Scmonth = nStr1[(int)l[1]];
-            cd.Scday = GetCDay((int)l[2]);
-            string smd = dt.ToString("MMdd");
-
-            string lmd = FormatDate(cd.Cmonth, cd.Cday);
-            for (int i = 0; i < solarTerm.Length; i++)
-            {
-                string s1 = GetSolarTermDay(dt.Year, i).ToString("MMdd");
-                if (s1.Equals(dt.ToString("MMdd")))
-                {
-                    cd.solarterm = solarTerm[i];
-                    break;
-                }
-            }
-            foreach (string s in sFtv)
-            {
-                string s1 = s.Substring(0, 4);
-                if (s1.Equals(smd))
-                {
-                    cd.cnFtvs = s.Substring(4, s.Length - 4);
-                    break;
-                }
-            }
-            foreach (string s in lFtv)
-            {
-                string s1 = s.Substring(0, 4);
-                if (s1.Equals(lmd))
-                {
-                    cd.cnFtvl = s.Substring(4, s.Length - 4);
-                    break;
-                }
-            }
-            dt = dt.AddDays(1);
-            year = dt.Year;
-            month = dt.Month;
-            date = dt.Day;
-            l = calElement(year, month, date);
-            lmd = FormatDate((int)l[1], (int)l[2]);
-            if (lmd.Equals("0101")) cd.cnFtvl = "除夕";
-            return cd;
-        }
-
-        #endregion
-    }
-}

+ 1461 - 79
Masuit.Tools/DateTimeExt/ChineseCalendar.cs

@@ -1,162 +1,1544 @@
 using System;
-using System.Globalization;
+using System.Collections.Generic;
+using System.Linq;
 
 namespace Masuit.Tools.DateTimeExt
 {
     /// <summary>
-    /// 中国农历年处理类用net自带类
+    /// 中国农历类 支持 1900.1.31日起至 2069.12.31日止的数据
     /// </summary>
-    public static class ChineseCalendar
+    /// <remarks>
+    /// 本程序使用数据来源于网上的万年历查询,并综合了一些其它数据
+    /// </remarks>
+    public class ChineseCalendar
     {
+        private class ChineseCalendarException : Exception
+        {
+            public ChineseCalendarException(string msg) : base(msg)
+            {
+            }
+        }
+
+        #region 内部变量
+
+        private DateTime _date;
+        private readonly DateTime _datetime;
+        private readonly int _cYear;
+        private readonly int _cMonth;
+        private readonly int _cDay;
+
+        /// <summary>
+        /// 当月是否闰月
+        /// </summary>
+        private readonly bool _cIsLeapMonth;
+
+        /// <summary>
+        /// 当年是否有闰月
+        /// </summary>
+        private readonly bool _cIsLeapYear;
+
+        #endregion
+
+        #region 基础数据
+
+        private const int MinYear = 1900;
+        private const int MaxYear = 2050;
+        private static readonly DateTime MinDay = new DateTime(1900, 1, 30);
+        private static readonly DateTime MaxDay = new DateTime(2049, 12, 31);
+        private const int GanZhiStartYear = 1864; //干支计算起始年
+        private static readonly DateTime GanZhiStartDay = new DateTime(1899, 12, 22); //起始日
+        private const string HzNum = "零一二三四五六七八九";
+        private const int AnimalStartYear = 1900; //1900年为鼠年
+        private static readonly DateTime ChineseConstellationReferDay = new DateTime(2007, 9, 13); //28星宿参考值,本日为角
+
+        /// <summary>
+        /// 来源于网上的农历数据
+        /// </summary>
+        /// <remarks>
+        /// 数据结构如下,共使用17位数据
+        /// 第17位:表示闰月天数,0表示29天   1表示30天
+        /// 第16位-第5位(共12位)表示12个月,其中第16位表示第一月,如果该月为30天则为1,29天为0
+        /// 第4位-第1位(共4位)表示闰月是哪个月,如果当年没有闰月,则置0
+        ///</remarks>
+        private static readonly int[] LunarDateArray =
+        {
+            0x04BD8,
+            0x04AE0,
+            0x0A570,
+            0x054D5,
+            0x0D260,
+            0x0D950,
+            0x16554,
+            0x056A0,
+            0x09AD0,
+            0x055D2,
+            0x04AE0,
+            0x0A5B6,
+            0x0A4D0,
+            0x0D250,
+            0x1D255,
+            0x0B540,
+            0x0D6A0,
+            0x0ADA2,
+            0x095B0,
+            0x14977,
+            0x04970,
+            0x0A4B0,
+            0x0B4B5,
+            0x06A50,
+            0x06D40,
+            0x1AB54,
+            0x02B60,
+            0x09570,
+            0x052F2,
+            0x04970,
+            0x06566,
+            0x0D4A0,
+            0x0EA50,
+            0x06E95,
+            0x05AD0,
+            0x02B60,
+            0x186E3,
+            0x092E0,
+            0x1C8D7,
+            0x0C950,
+            0x0D4A0,
+            0x1D8A6,
+            0x0B550,
+            0x056A0,
+            0x1A5B4,
+            0x025D0,
+            0x092D0,
+            0x0D2B2,
+            0x0A950,
+            0x0B557,
+            0x06CA0,
+            0x0B550,
+            0x15355,
+            0x04DA0,
+            0x0A5B0,
+            0x14573,
+            0x052B0,
+            0x0A9A8,
+            0x0E950,
+            0x06AA0,
+            0x0AEA6,
+            0x0AB50,
+            0x04B60,
+            0x0AAE4,
+            0x0A570,
+            0x05260,
+            0x0F263,
+            0x0D950,
+            0x05B57,
+            0x056A0,
+            0x096D0,
+            0x04DD5,
+            0x04AD0,
+            0x0A4D0,
+            0x0D4D4,
+            0x0D250,
+            0x0D558,
+            0x0B540,
+            0x0B6A0,
+            0x195A6,
+            0x095B0,
+            0x049B0,
+            0x0A974,
+            0x0A4B0,
+            0x0B27A,
+            0x06A50,
+            0x06D40,
+            0x0AF46,
+            0x0AB60,
+            0x09570,
+            0x04AF5,
+            0x04970,
+            0x064B0,
+            0x074A3,
+            0x0EA50,
+            0x06B58,
+            0x055C0,
+            0x0AB60,
+            0x096D5,
+            0x092E0,
+            0x0C960,
+            0x0D954,
+            0x0D4A0,
+            0x0DA50,
+            0x07552,
+            0x056A0,
+            0x0ABB7,
+            0x025D0,
+            0x092D0,
+            0x0CAB5,
+            0x0A950,
+            0x0B4A0,
+            0x0BAA4,
+            0x0AD50,
+            0x055D9,
+            0x04BA0,
+            0x0A5B0,
+            0x15176,
+            0x052B0,
+            0x0A930,
+            0x07954,
+            0x06AA0,
+            0x0AD50,
+            0x05B52,
+            0x04B60,
+            0x0A6E6,
+            0x0A4E0,
+            0x0D260,
+            0x0EA65,
+            0x0D530,
+            0x05AA0,
+            0x076A3,
+            0x096D0,
+            0x04BD7,
+            0x04AD0,
+            0x0A4D0,
+            0x1D0B6,
+            0x0D250,
+            0x0D520,
+            0x0DD45,
+            0x0B5A0,
+            0x056D0,
+            0x055B2,
+            0x049B0,
+            0x0A577,
+            0x0A4B0,
+            0x0AA50,
+            0x1B255,
+            0x06D20,
+            0x0ADA0,
+            0x14B63
+        };
+
+        /// <summary>
+        /// 星座
+        /// </summary>
+        private static readonly string[] ConstellationName =
+        {
+            "白羊座",
+            "金牛座",
+            "双子座",
+            "巨蟹座",
+            "狮子座",
+            "处女座",
+            "天秤座",
+            "天蝎座",
+            "射手座",
+            "摩羯座",
+            "水瓶座",
+            "双鱼座"
+        };
+
+        /// <summary>
+        /// 二十四节气
+        /// </summary>
+        private static readonly string[] LunarHolidayName =
+        {
+            "小寒",
+            "大寒",
+            "立春",
+            "雨水",
+            "惊蛰",
+            "春分",
+            "清明",
+            "谷雨",
+            "立夏",
+            "小满",
+            "芒种",
+            "夏至",
+            "小暑",
+            "大暑",
+            "立秋",
+            "处暑",
+            "白露",
+            "秋分",
+            "寒露",
+            "霜降",
+            "立冬",
+            "小雪",
+            "大雪",
+            "冬至"
+        };
+
+        /// <summary>
+        /// 二十八星宿
+        /// </summary>
+        private static readonly string[] ChineseConstellationName =
+        {
+            //四        五      六         日        一      二      三  
+            "角木蛟",
+            "亢金龙",
+            "女土蝠",
+            "房日兔",
+            "心月狐",
+            "尾火虎",
+            "箕水豹",
+            "斗木獬",
+            "牛金牛",
+            "氐土貉",
+            "虚日鼠",
+            "危月燕",
+            "室火猪",
+            "壁水獝",
+            "奎木狼",
+            "娄金狗",
+            "胃土彘",
+            "昴日鸡",
+            "毕月乌",
+            "觜火猴",
+            "参水猿",
+            "井木犴",
+            "鬼金羊",
+            "柳土獐",
+            "星日马",
+            "张月鹿",
+            "翼火蛇",
+            "轸水蚓"
+        };
+
+        #region 节气数据
+
+        /// <summary>
+        /// 节气数据
+        /// </summary>
+        private static readonly string[] SolarTerm =
+        {
+            "小寒",
+            "大寒",
+            "立春",
+            "雨水",
+            "惊蛰",
+            "春分",
+            "清明",
+            "谷雨",
+            "立夏",
+            "小满",
+            "芒种",
+            "夏至",
+            "小暑",
+            "大暑",
+            "立秋",
+            "处暑",
+            "白露",
+            "秋分",
+            "寒露",
+            "霜降",
+            "立冬",
+            "小雪",
+            "大雪",
+            "冬至"
+        };
+
+        private static readonly int[] STermInfo =
+        {
+            0,
+            21208,
+            42467,
+            63836,
+            85337,
+            107014,
+            128867,
+            150921,
+            173149,
+            195551,
+            218072,
+            240693,
+            263343,
+            285989,
+            308563,
+            331033,
+            353350,
+            375494,
+            397447,
+            419210,
+            440795,
+            462224,
+            483532,
+            504758
+        };
+
+        #endregion
+
+        #region 农历相关数据
+
+        private const string GanStr = "甲乙丙丁戊己庚辛壬癸";
+        private const string ZhiStr = "子丑寅卯辰巳午未申酉戌亥";
+        private const string AnimalStr = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
+        private const string NStr1 = "日一二三四五六七八九";
+        private const string NStr2 = "初十廿卅";
+
+        private static readonly string[] MonthString =
+        {
+            "出错",
+            "正月",
+            "二月",
+            "三月",
+            "四月",
+            "五月",
+            "六月",
+            "七月",
+            "八月",
+            "九月",
+            "十月",
+            "十一月",
+            "腊月"
+        };
+
+        #endregion
+
+        #region 节日数据
+
+        /// <summary>
+        /// 按公历计算的节日
+        /// </summary>
+        public static HashSet<DateInfoStruct> SolarHolidayInfo { get; } = new HashSet<DateInfoStruct>
+        {
+            new DateInfoStruct(1, 1, 1, "元旦"),
+            new DateInfoStruct(2, 2, 0, "世界湿地日"),
+            new DateInfoStruct(2, 10, 0, "国际气象节"),
+            new DateInfoStruct(2, 14, 0, "情人节"),
+            new DateInfoStruct(3, 1, 0, "国际海豹日"),
+            new DateInfoStruct(3, 5, 0, "学雷锋纪念日"),
+            new DateInfoStruct(3, 8, 0, "妇女节"),
+            new DateInfoStruct(3, 12, 0, "植树节 孙中山逝世纪念日"),
+            new DateInfoStruct(3, 14, 0, "国际警察日"),
+            new DateInfoStruct(3, 15, 0, "消费者权益日"),
+            new DateInfoStruct(3, 17, 0, "中国国医节 国际航海日"),
+            new DateInfoStruct(3, 21, 0, "世界森林日 消除种族歧视国际日 世界儿歌日"),
+            new DateInfoStruct(3, 22, 0, "世界水日"),
+            new DateInfoStruct(3, 24, 0, "世界防治结核病日"),
+            new DateInfoStruct(4, 1, 0, "愚人节"),
+            new DateInfoStruct(4, 5, 1, "清明节"),
+            new DateInfoStruct(4, 7, 0, "世界卫生日"),
+            new DateInfoStruct(4, 22, 0, "世界地球日"),
+            new DateInfoStruct(5, 1, 1, "劳动节"),
+            new DateInfoStruct(5, 4, 0, "青年节"),
+            new DateInfoStruct(5, 8, 0, "世界红十字日"),
+            new DateInfoStruct(5, 12, 0, "国际护士节"),
+            new DateInfoStruct(5, 31, 0, "世界无烟日"),
+            new DateInfoStruct(6, 1, 0, "国际儿童节"),
+            new DateInfoStruct(6, 5, 0, "世界环境保护日"),
+            new DateInfoStruct(6, 26, 0, "国际禁毒日"),
+            new DateInfoStruct(7, 1, 0, "建党节 香港回归纪念 世界建筑日"),
+            new DateInfoStruct(7, 11, 0, "世界人口日"),
+            new DateInfoStruct(8, 1, 0, "建军节"),
+            new DateInfoStruct(8, 8, 0, "中国男子节 父亲节"),
+            new DateInfoStruct(8, 15, 0, "抗日战争胜利纪念"),
+            new DateInfoStruct(9, 9, 0, "  逝世纪念"),
+            new DateInfoStruct(9, 10, 0, "教师节"),
+            new DateInfoStruct(9, 18, 0, "九·一八事变纪念日"),
+            new DateInfoStruct(9, 20, 0, "国际爱牙日"),
+            new DateInfoStruct(9, 27, 0, "世界旅游日"),
+            new DateInfoStruct(9, 28, 0, "孔子诞辰"),
+            new DateInfoStruct(10, 1, 7, "国庆节 国际音乐日"),
+            new DateInfoStruct(10, 24, 0, "联合国日"),
+            new DateInfoStruct(11, 10, 0, "世界青年节"),
+            new DateInfoStruct(11, 12, 0, "孙中山诞辰纪念"),
+            new DateInfoStruct(12, 1, 0, "世界艾滋病日"),
+            new DateInfoStruct(12, 3, 0, "世界残疾人日"),
+            new DateInfoStruct(12, 20, 0, "澳门回归纪念"),
+            new DateInfoStruct(12, 24, 0, "平安夜"),
+            new DateInfoStruct(12, 25, 0, "圣诞节"),
+            new DateInfoStruct(12, 26, 0, " 诞辰纪念")
+        };
+
+        /// <summary>
+        /// 按农历计算的节日
+        /// </summary>
+        public static HashSet<DateInfoStruct> LunarHolidayInfo { get; } = new HashSet<DateInfoStruct>
+        {
+            new DateInfoStruct(1, 1, 6, "春节"),
+            new DateInfoStruct(1, 15, 0, "元宵节"),
+            new DateInfoStruct(5, 5, 1, "端午节"),
+            new DateInfoStruct(7, 7, 0, "七夕情人节"),
+            new DateInfoStruct(7, 15, 0, "中元节 盂兰盆节"),
+            new DateInfoStruct(8, 15, 1, "中秋节"),
+            new DateInfoStruct(9, 9, 0, "重阳节"),
+            new DateInfoStruct(12, 8, 0, "腊八节"),
+            new DateInfoStruct(12, 23, 0, "北方小年(扫房)"),
+            new DateInfoStruct(12, 24, 0, "南方小年(掸尘)"),
+            //new HolidayStruct(12, 30, 0, "除夕")  //注意除夕需要其它方法进行计算
+        };
+
+        /// <summary>
+        /// 按农历计算的节日
+        /// </summary>
+        public static HashSet<DateTime> WorkDays { get; } = new HashSet<DateTime>();
+
+        private static readonly WeekHolidayStruct[] WHolidayInfo =
+        {
+            new WeekHolidayStruct(5, 2, 1, "母亲节"),
+            new WeekHolidayStruct(5, 3, 1, "全国助残日"),
+            new WeekHolidayStruct(6, 3, 1, "父亲节"),
+            new WeekHolidayStruct(9, 3, 3, "国际和平日"),
+            new WeekHolidayStruct(9, 4, 1, "国际聋人节"),
+            new WeekHolidayStruct(10, 1, 2, "国际住房日"),
+            new WeekHolidayStruct(10, 1, 4, "国际减轻自然灾害日"),
+            new WeekHolidayStruct(11, 4, 5, "感恩节")
+        };
+
+        #endregion
+
+        #endregion
+
+        /// <summary>
+        /// 用一个标准的公历日期来初使化
+        /// </summary>
+        /// <param name="dt"></param>
+        public ChineseCalendar(DateTime dt)
+        {
+            int i;
+            CheckDateLimit(dt);
+            _date = dt.Date;
+            _datetime = dt;
+            //农历日期计算部分
+            var temp = 0;
+            TimeSpan ts = _date - MinDay; //计算两天的基本差距
+            var offset = ts.Days;
+            for (i = MinYear; i <= MaxYear; i++)
+            {
+                temp = GetChineseYearDays(i); //求当年农历年天数
+                if (offset - temp < 1)
+                {
+                    break;
+                }
+
+                offset = offset - temp;
+            }
+
+            _cYear = i;
+            var leap = GetChineseLeapMonth(_cYear);
+            //设定当年是否有闰月
+            _cIsLeapYear = leap > 0;
+            _cIsLeapMonth = false;
+            for (i = 1; i <= 12; i++)
+            {
+                //闰月
+                if (leap > 0 && i == leap + 1 && _cIsLeapMonth == false)
+                {
+                    _cIsLeapMonth = true;
+                    i = i - 1;
+                    temp = GetChineseLeapMonthDays(_cYear); //计算闰月天数
+                }
+                else
+                {
+                    _cIsLeapMonth = false;
+                    temp = GetChineseMonthDays(_cYear, i); //计算非闰月天数
+                }
+
+                offset = offset - temp;
+                if (offset <= 0)
+                {
+                    break;
+                }
+            }
+
+            offset = offset + temp;
+            _cMonth = i;
+            _cDay = offset;
+        }
+
+        /// <summary>
+        /// 用农历的日期来初使化
+        /// </summary>
+        /// <param name="cy">农历年</param>
+        /// <param name="cm">农历月</param>
+        /// <param name="cd">农历日</param>
+        /// <param name="leapMonthFlag">闰月标志</param>
+        public ChineseCalendar(int cy, int cm, int cd, bool leapMonthFlag)
+        {
+            int i, temp;
+            CheckChineseDateLimit(cy, cm, cd, leapMonthFlag);
+            _cYear = cy;
+            _cMonth = cm;
+            _cDay = cd;
+            var offset = 0;
+            for (i = MinYear; i < cy; i++)
+            {
+                temp = GetChineseYearDays(i); //求当年农历年天数
+                offset = offset + temp;
+            }
+
+            var leap = GetChineseLeapMonth(cy);
+            _cIsLeapYear = leap != 0;
+            _cIsLeapMonth = cm == leap && leapMonthFlag;
+            if (_cIsLeapYear == false || cm < leap) //当年没有闰月||计算月份小于闰月     
+            {
+                for (i = 1; i < cm; i++)
+                {
+                    temp = GetChineseMonthDays(cy, i); //计算非闰月天数
+                    offset = offset + temp;
+                }
+
+                //检查日期是否大于最大天
+                if (cd > GetChineseMonthDays(cy, cm))
+                {
+                    throw new ChineseCalendarException("不合法的农历日期");
+                }
+
+                offset = offset + cd; //加上当月的天数
+            }
+            else //是闰年,且计算月份大于或等于闰月
+            {
+                for (i = 1; i < cm; i++)
+                {
+                    temp = GetChineseMonthDays(cy, i); //计算非闰月天数
+                    offset = offset + temp;
+                }
+
+                if (cm > leap) //计算月大于闰月
+                {
+                    temp = GetChineseLeapMonthDays(cy); //计算闰月天数
+                    offset = offset + temp; //加上闰月天数
+                    if (cd > GetChineseMonthDays(cy, cm))
+                    {
+                        throw new ChineseCalendarException("不合法的农历日期");
+                    }
+
+                    offset = offset + cd;
+                }
+                else //计算月等于闰月
+                {
+                    //如果需要计算的是闰月,则应首先加上与闰月对应的普通月的天数
+                    if (_cIsLeapMonth) //计算月为闰月
+                    {
+                        temp = GetChineseMonthDays(cy, cm); //计算非闰月天数
+                        offset = offset + temp;
+                    }
+
+                    if (cd > GetChineseLeapMonthDays(cy))
+                    {
+                        throw new ChineseCalendarException("不合法的农历日期");
+                    }
+
+                    offset = offset + cd;
+                }
+            }
+
+            _date = MinDay.AddDays(offset);
+        }
+
+        #region 私有函数
+
+        /// <summary>
+        /// 传回农历 y年m月的总天数
+        /// </summary>
+        /// <param name="year"></param>
+        /// <param name="month"></param>
+        /// <returns></returns>
+        private int GetChineseMonthDays(int year, int month)
+        {
+            if (BitTest32((LunarDateArray[year - MinYear] & 0x0000FFFF), (16 - month)))
+            {
+                return 30;
+            }
+
+            return 29;
+        }
+
+        /// <summary>
+        /// 传回农历 y年闰哪个月 1-12 , 没闰传回 0
+        /// </summary>
+        /// <param name="year"></param>
+        /// <returns></returns>
+        private int GetChineseLeapMonth(int year)
+        {
+            return LunarDateArray[year - MinYear] & 0xF;
+        }
+
         /// <summary>
-        /// 实例化一个  ChineseLunisolarCalendar
+        /// 传回农历 y年闰月的天数
         /// </summary>
-        private static ChineseLunisolarCalendar cCalendar = new ChineseLunisolarCalendar();
+        /// <param name="year"></param>
+        /// <returns></returns>
+        private int GetChineseLeapMonthDays(int year)
+        {
+            if (GetChineseLeapMonth(year) != 0)
+            {
+                return (LunarDateArray[year - MinYear] & 0x10000) != 0 ? 30 : 29;
+            }
+
+            return 0;
+        }
+
+        /// <summary>
+        /// 取农历年一年的天数
+        /// </summary>
+        /// <param name="year"></param>
+        /// <returns></returns>
+        private int GetChineseYearDays(int year)
+        {
+            var sumDay = 348;
+            var i = 0x8000;
+            var info = LunarDateArray[year - MinYear] & 0x0FFFF;
+            //计算12个月中有多少天为30天
+            for (int m = 0; m < 12; m++)
+            {
+                var f = info & i;
+                if (f != 0)
+                {
+                    sumDay++;
+                }
+
+                i = i >> 1;
+            }
+
+            return sumDay + GetChineseLeapMonthDays(year);
+        }
+
+        /// <summary>
+        /// 获得当前时间的时辰
+        /// </summary>
+        /// <param name="dt"></param>
+        /// <returns></returns>
+        /// 
+        private string GetChineseHour(DateTime dt)
+        {
+            //计算时辰的地支
+            var hour = dt.Hour;
+            var minute = dt.Minute;
+            if (minute != 0) hour += 1;
+            var offset = hour / 2;
+            if (offset >= 12) offset = 0;
+            //计算天干
+            TimeSpan ts = _date - GanZhiStartDay;
+            var i = ts.Days % 60;
+            var indexGan = ((i % 10 + 1) * 2 - 1) % 10 - 1;
+            var tmpGan = GanStr.Substring(indexGan) + GanStr.Substring(0, indexGan + 2);
+            return tmpGan[offset].ToString() + ZhiStr[offset];
+        }
+
+        /// <summary>
+        /// 检查公历日期是否符合要求
+        /// </summary>
+        /// <param name="dt"></param>
+        private void CheckDateLimit(DateTime dt)
+        {
+            if ((dt < MinDay) || (dt > MaxDay))
+            {
+                throw new ChineseCalendarException("超出可转换的日期");
+            }
+        }
+
+        /// <summary>
+        /// 检查农历日期是否合理
+        /// </summary>
+        /// <param name="year"></param>
+        /// <param name="month"></param>
+        /// <param name="day"></param>
+        /// <param name="leapMonth"></param>
+        private void CheckChineseDateLimit(int year, int month, int day, bool leapMonth)
+        {
+            if ((year < MinYear) || (year > MaxYear))
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+
+            if ((month < 1) || (month > 12))
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+
+            if ((day < 1) || (day > 30)) //中国的月最多30天
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+
+            int leap = GetChineseLeapMonth(year); // 计算该年应该闰哪个月
+            if (leapMonth && month != leap)
+            {
+                throw new ChineseCalendarException("非法农历日期");
+            }
+        }
+
+        /// <summary>
+        /// 将0-9转成汉字形式
+        /// </summary>
+        /// <param name="n"></param>
+        /// <returns></returns>
+        private string ConvertNumToChineseNum(char n)
+        {
+            if ((n < '0') || (n > '9')) return "";
+            switch (n)
+            {
+                case '0':
+                    return HzNum[0].ToString();
+                case '1':
+                    return HzNum[1].ToString();
+                case '2':
+                    return HzNum[2].ToString();
+                case '3':
+                    return HzNum[3].ToString();
+                case '4':
+                    return HzNum[4].ToString();
+                case '5':
+                    return HzNum[5].ToString();
+                case '6':
+                    return HzNum[6].ToString();
+                case '7':
+                    return HzNum[7].ToString();
+                case '8':
+                    return HzNum[8].ToString();
+                case '9':
+                    return HzNum[9].ToString();
+                default:
+                    return "";
+            }
+        }
+
+        /// <summary>
+        /// 测试某位是否为真
+        /// </summary>
+        /// <param name="num"></param>
+        /// <param name="bitpostion"></param>
+        /// <returns></returns>
+        private bool BitTest32(int num, int bitpostion)
+        {
+            if ((bitpostion > 31) || (bitpostion < 0))
+                throw new Exception("Error Param: bitpostion[0-31]:" + bitpostion.ToString());
+            int bit = 1 << bitpostion;
+            if ((num & bit) == 0)
+            {
+                return false;
+            }
+            else
+            {
+                return true;
+            }
+        }
+
+        /// <summary>
+        /// 将星期几转成数字表示
+        /// </summary>
+        /// <param name="dayOfWeek"></param>
+        /// <returns></returns>
+        private int ConvertDayOfWeek(DayOfWeek dayOfWeek)
+        {
+            switch (dayOfWeek)
+            {
+                case DayOfWeek.Sunday:
+                    return 1;
+                case DayOfWeek.Monday:
+                    return 2;
+                case DayOfWeek.Tuesday:
+                    return 3;
+                case DayOfWeek.Wednesday:
+                    return 4;
+                case DayOfWeek.Thursday:
+                    return 5;
+                case DayOfWeek.Friday:
+                    return 6;
+                case DayOfWeek.Saturday:
+                    return 7;
+                default:
+                    return 0;
+            }
+        }
+
+        /// <summary>
+        /// 比较当天是不是指定的第周几
+        /// </summary>
+        /// <param name="date"></param>
+        /// <param name="month"></param>
+        /// <param name="week"></param>
+        /// <param name="day"></param>
+        /// <returns></returns>
+        private bool CompareWeekDayHoliday(DateTime date, int month, int week, int day)
+        {
+            bool ret = false;
+            if (date.Month == month) //月份相同
+            {
+                if (ConvertDayOfWeek(date.DayOfWeek) == day) //星期几相同
+                {
+                    DateTime firstDay = new DateTime(date.Year, date.Month, 1); //生成当月第一天
+                    int i = ConvertDayOfWeek(firstDay.DayOfWeek);
+                    int firWeekDays = 7 - ConvertDayOfWeek(firstDay.DayOfWeek) + 1; //计算第一周剩余天数
+                    if (i > day)
+                    {
+                        if ((week - 1) * 7 + day + firWeekDays == date.Day)
+                        {
+                            ret = true;
+                        }
+                    }
+                    else
+                    {
+                        if (day + firWeekDays + (week - 2) * 7 == date.Day)
+                        {
+                            ret = true;
+                        }
+                    }
+                }
+            }
+
+            return ret;
+        }
+
+        #endregion
+
+        #region 节日
+
+        /// <summary>
+        /// 计算中国农历节日
+        /// </summary>
+        public string ChineseCalendarHoliday
+        {
+            get
+            {
+                string tempStr = "";
+                if (_cIsLeapMonth)
+                {
+                    return tempStr;
+                }
+
+                foreach (DateInfoStruct lh in LunarHolidayInfo)
+                {
+                    var end = lh.Recess > 0 ? lh.Day + lh.Recess - 1 : lh.Day + lh.Recess;
+                    if (lh.Month == _cMonth && _cDay >= lh.Day && _cDay <= end)
+                    {
+                        tempStr = lh.HolidayName;
+                        break;
+                    }
+                }
+
+                //对除夕进行特别处理
+                if (_cMonth != 12)
+                {
+                    return tempStr;
+                }
+
+                int i = GetChineseMonthDays(_cYear, 12); //计算当年农历12月的总天数
+                if (_cDay == i) //如果为最后一天
+                {
+                    tempStr = "除夕";
+                }
+
+                return tempStr;
+            }
+        }
 
         /// <summary>
-        /// 获取农历当前日期
+        /// 按某月第几周第几日计算的节日
         /// </summary>
-        /// <returns>当前农历日期</returns>
-        public static string GetChineseDateTimeNow(this DateTime dt) => GetChineseDateTime(dt);
+        public string WeekDayHoliday
+        {
+            get
+            {
+                string tempStr = "";
+                foreach (WeekHolidayStruct wh in WHolidayInfo)
+                {
+                    if (!CompareWeekDayHoliday(_date, wh.Month, wh.WeekAtMonth, wh.WeekDay))
+                    {
+                        continue;
+                    }
+
+                    tempStr = wh.HolidayName;
+                    break;
+                }
+
+                return tempStr;
+            }
+        }
 
         /// <summary>
-        /// 根据公历获取农历日期
+        /// 按公历日计算的节日
         /// </summary>
-        /// <param name="datetime">公历日期</param>
-        /// <returns>公历日期的字符串形式</returns>
-        public static string GetChineseDateTime(this DateTime datetime)
+        public string DateHoliday
         {
-            int lyear = cCalendar.GetYear(datetime);
-            int lmonth = cCalendar.GetMonth(datetime);
-            int lday = cCalendar.GetDayOfMonth(datetime);
-            //获取闰月, 0 则表示没有闰月
-            int leapMonth = cCalendar.GetLeapMonth(lyear);
-            bool isleap = false;
-            if (leapMonth > 0)
+            get
             {
-                if (leapMonth == lmonth)
+                string tempStr = "";
+                foreach (DateInfoStruct sh in SolarHolidayInfo)
                 {
-                    //闰月
-                    isleap = true;
-                    lmonth--;
+                    var end = sh.Recess > 0 ? sh.Day + sh.Recess - 1 : sh.Day + sh.Recess;
+                    if ((sh.Month == _date.Month) && _date.Day >= sh.Day && _date.Day <= end)
+                    {
+                        tempStr = sh.HolidayName;
+                        break;
+                    }
                 }
-                else if (lmonth > leapMonth)
+
+                return tempStr;
+            }
+        }
+
+        public bool IsHoliday => !IsWorkDay;
+
+        public bool IsWorkDay
+        {
+            get
+            {
+                bool isHoliday = false;
+                foreach (DateInfoStruct sh in SolarHolidayInfo)
                 {
-                    lmonth--;
+                    var end = sh.Recess > 0 ? sh.Day + sh.Recess - 1 : sh.Day + sh.Recess;
+                    if ((sh.Month == _date.Month) && _date.Day >= sh.Day && _date.Day <= end && sh.Recess > 0)
+                    {
+                        isHoliday = true;
+                        break;
+                    }
                 }
+
+                if (!isHoliday)
+                {
+                    foreach (DateInfoStruct lh in LunarHolidayInfo)
+                    {
+                        var end = lh.Recess > 0 ? lh.Day + lh.Recess - 1 : lh.Day + lh.Recess;
+                        if (lh.Month == _cMonth && _cDay >= lh.Day && _cDay <= end && lh.Recess > 0)
+                        {
+                            isHoliday = true;
+                            break;
+                        }
+                    }
+
+                    //对除夕进行特别处理
+                    if (_cMonth == 12)
+                    {
+                        int i = GetChineseMonthDays(_cYear, 12); //计算当年农历12月的总天数
+                        if (_cDay == i) //如果为最后一天
+                        {
+                            isHoliday = true;
+                        }
+                    }
+                }
+
+                return !isHoliday && !IsWeekend() || WorkDays.Any(s => s.Date == _date);
             }
-            return string.Concat(GetLunisolarYear(lyear), "年", isleap ? "闰" : string.Empty, GetLunisolarMonth(lmonth), "月", GetLunisolarDay(lday));
         }
 
         /// <summary>
-        /// 返回农历日期
+        /// 是否是周末
         /// </summary>
-        public static string Now => DateTime.Now.GetChineseDateTimeNow();
+        /// <returns></returns>
+        private bool IsWeekend()
+        {
+            return _date.DayOfWeek == DayOfWeek.Saturday || _date.DayOfWeek == DayOfWeek.Sunday;
+        }
+
+        #endregion
+
+        #region 公历日期
 
         /// <summary>
-        /// 最大支持日期
+        /// 取对应的公历日期
         /// </summary>
-        public static DateTime MaxSupportedDateTime => cCalendar.MaxSupportedDateTime;
+        public DateTime Date
+        {
+            get => _date;
+            set => _date = value;
+        }
 
         /// <summary>
-        /// 最小支持日期
+        /// 取星期几
         /// </summary>
-        public static DateTime MinSupportedDateTime { get; } = cCalendar.MinSupportedDateTime;
+        public DayOfWeek WeekDay => _date.DayOfWeek;
 
         /// <summary>
-        /// 返回生肖
+        /// 周几的字符
         /// </summary>
-        /// <param name="datetime">公历日期</param>
-        /// <returns>生肖</returns>
-        public static string GetShengXiao(this DateTime datetime) => shengxiao[cCalendar.GetTerrestrialBranch(cCalendar.GetSexagenaryYear(datetime)) - 1];
+        public string WeekDayStr
+        {
+            get
+            {
+                switch (_date.DayOfWeek)
+                {
+                    case DayOfWeek.Sunday:
+                        return "星期日";
+                    case DayOfWeek.Monday:
+                        return "星期一";
+                    case DayOfWeek.Tuesday:
+                        return "星期二";
+                    case DayOfWeek.Wednesday:
+                        return "星期三";
+                    case DayOfWeek.Thursday:
+                        return "星期四";
+                    case DayOfWeek.Friday:
+                        return "星期五";
+                    default:
+                        return "星期六";
+                }
+            }
+        }
 
-        #region 农历年
+        /// <summary>
+        /// 公历日期中文表示法 如一九九七年七月一日
+        /// </summary>
+        public string DateString => "公元" + _date.ToLongDateString();
 
         /// <summary>
-        /// 十天干
+        /// 当前是否公历闰年
         /// </summary>
-        private static string[] tiangan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
+        public bool IsLeapYear => DateTime.IsLeapYear(_date.Year);
 
         /// <summary>
-        /// 十二地支
+        /// 28星宿计算
         /// </summary>
-        private static string[] dizhi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
+        public string ChineseConstellation
+        {
+            get
+            {
+                TimeSpan ts = _date - ChineseConstellationReferDay;
+                var offset = ts.Days;
+                var modStarDay = offset % 28;
+                return (modStarDay >= 0 ? ChineseConstellationName[modStarDay] : ChineseConstellationName[27 + modStarDay]);
+            }
+        }
 
         /// <summary>
-        /// 十二生肖
+        /// 时辰
         /// </summary>
-        private static string[] shengxiao = { "鼠", "牛", "虎", "免", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
+        public string ChineseHour => GetChineseHour(_datetime);
+
+        #endregion
+
+        #region 农历日期
+
+        /// <summary>
+        /// 农历今天
+        /// </summary>
+        public static ChineseCalendar Today => new ChineseCalendar(DateTime.Today);
+
+        /// <summary>
+        /// 是否闰月
+        /// </summary>
+        public bool IsChineseLeapMonth => _cIsLeapMonth;
+
+        /// <summary>
+        /// 当年是否有闰月
+        /// </summary>
+        public bool IsChineseLeapYear => _cIsLeapYear;
+
+        /// <summary>
+        /// 农历日
+        /// </summary>
+        public int ChineseDay => _cDay;
+
+        /// <summary>
+        /// 农历日中文表示
+        /// </summary>
+        public string ChineseDayString
+        {
+            get
+            {
+                switch (_cDay)
+                {
+                    case 0:
+                        return "";
+                    case 10:
+                        return "初十";
+                    case 20:
+                        return "二十";
+                    case 30:
+                        return "三十";
+                    default:
+                        return NStr2[_cDay / 10] + NStr1[_cDay % 10].ToString();
+                }
+            }
+        }
+
+        /// <summary>
+        /// 农历的月份
+        /// </summary>
+        public int ChineseMonth => _cMonth;
+
+        /// <summary>
+        /// 农历月份字符串
+        /// </summary>
+        public string ChineseMonthString => MonthString[_cMonth];
+
+        /// <summary>
+        /// 取农历年份
+        /// </summary>
+        public int ChineseYear => _cYear;
+
+        /// <summary>
+        /// 取农历年字符串如,一九九七年
+        /// </summary>
+        public string ChineseYearString
+        {
+            get
+            {
+                string tempStr = "";
+                string num = _cYear.ToString();
+                for (int i = 0; i < 4; i++)
+                {
+                    tempStr += ConvertNumToChineseNum(num[i]);
+                }
+
+                return tempStr + "年";
+            }
+        }
+
+        /// <summary>
+        /// 取农历日期表示法:农历一九九七年正月初五
+        /// </summary>
+        public string ChineseDateString
+        {
+            get
+            {
+                if (_cIsLeapMonth)
+                {
+                    return "农历" + ChineseYearString + "闰" + ChineseMonthString + ChineseDayString;
+                }
+
+                return "农历" + ChineseYearString + ChineseMonthString + ChineseDayString;
+            }
+        }
+
+        /// <summary>
+        /// 定气法计算二十四节气,二十四节气是按地球公转来计算的,并非是阴历计算的
+        /// </summary>
+        /// <remarks>
+        /// 节气的定法有两种。古代历法采用的称为"恒气",即按时间把一年等分为24份,
+        /// 每一节气平均得15天有余,所以又称"平气"。现代农历采用的称为"定气",即
+        /// 按地球在轨道上的位置为标准,一周360°,两节气之间相隔15°。由于冬至时地
+        /// 球位于近日点附近,运动速度较快,因而太阳在黄道上移动15°的时间不到15天。
+        /// 夏至前后的情况正好相反,太阳在黄道上移动较慢,一个节气达16天之多。采用
+        /// 定气时可以保证春、秋两分必然在昼夜平分的那两天。
+        /// </remarks>
+        public string ChineseTwentyFourDay
+        {
+            get
+            {
+                DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
+                string tempStr = "";
+                var y = _date.Year;
+                for (int i = 1; i <= 24; i++)
+                {
+                    var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
+                    var newDate = baseDateAndTime.AddMinutes(num);
+                    if (newDate.DayOfYear != _date.DayOfYear)
+                    {
+                        continue;
+                    }
+
+                    tempStr = SolarTerm[i - 1];
+                    break;
+                }
+
+                return tempStr;
+            }
+        }
+
+        //当前日期前一个最近节气
+        public string ChineseTwentyFourPrevDay
+        {
+            get
+            {
+                DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
+                string tempStr = "";
+                var y = _date.Year;
+                for (int i = 24; i >= 1; i--)
+                {
+                    var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
+                    var newDate = baseDateAndTime.AddMinutes(num);
+                    if (newDate.DayOfYear < _date.DayOfYear)
+                    {
+                        tempStr = $"{SolarTerm[i - 1]}[{newDate:yyyy-MM-dd}]";
+                        break;
+                    }
+                }
+
+                return tempStr;
+            }
+        }
+
+        //当前日期后一个最近节气
+        public string ChineseTwentyFourNextDay
+        {
+            get
+            {
+                DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
+                string tempStr = "";
+                var y = _date.Year;
+                for (int i = 1; i <= 24; i++)
+                {
+                    var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
+                    var newDate = baseDateAndTime.AddMinutes(num);
+                    if (newDate.DayOfYear > _date.DayOfYear)
+                    {
+                        tempStr = $"{SolarTerm[i - 1]}[{newDate:yyyy-MM-dd}]";
+                        break;
+                    }
+                }
+
+                return tempStr;
+            }
+        }
+
+        #endregion
+
+        #region 星座
 
         /// <summary>
-        /// 返回农历天干地支年
+        /// 计算指定日期的星座序号 
         /// </summary>
-        /// <param name="year">农历年</param>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
-        /// <returns>天干地支年</returns>
-        public static string GetLunisolarYear(int year)
+        /// <returns></returns>
+        public string Constellation
         {
-            if (year > 3)
+            get
             {
-                int tgIndex = (year - 4) % 10;
-                int dzIndex = (year - 4) % 12;
-                return string.Concat(tiangan[tgIndex], dizhi[dzIndex], "[", shengxiao[dzIndex], "]");
+                int index;
+                var m = _date.Month;
+                var d = _date.Day;
+                var y = m * 100 + d;
+                if (((y >= 321) && (y <= 419)))
+                {
+                    index = 0;
+                }
+                else if ((y >= 420) && (y <= 520))
+                {
+                    index = 1;
+                }
+                else if ((y >= 521) && (y <= 620))
+                {
+                    index = 2;
+                }
+                else if ((y >= 621) && (y <= 722))
+                {
+                    index = 3;
+                }
+                else if ((y >= 723) && (y <= 822))
+                {
+                    index = 4;
+                }
+                else if ((y >= 823) && (y <= 922))
+                {
+                    index = 5;
+                }
+                else if ((y >= 923) && (y <= 1022))
+                {
+                    index = 6;
+                }
+                else if ((y >= 1023) && (y <= 1121))
+                {
+                    index = 7;
+                }
+                else if ((y >= 1122) && (y <= 1221))
+                {
+                    index = 8;
+                }
+                else if ((y >= 1222) || (y <= 119))
+                {
+                    index = 9;
+                }
+                else if ((y >= 120) && (y <= 218))
+                {
+                    index = 10;
+                }
+                else if ((y >= 219) && (y <= 320))
+                {
+                    index = 11;
+                }
+                else
+                {
+                    index = 0;
+                }
+
+                return ConstellationName[index];
             }
-            throw new ArgumentOutOfRangeException("无效的年份!");
         }
 
         #endregion
 
-        #region 农历月
+        #region 属相
 
         /// <summary>
-        /// 农历月
+        /// 计算属相的索引,注意虽然属相是以农历年来区别的,但是目前在实际使用中是按公历来计算的
+        /// 鼠年为1,其它类推
         /// </summary>
-        private static string[] months = { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二(腊)" };
+        public int Animal
+        {
+            get
+            {
+                int offset = _date.Year - AnimalStartYear;
+                return (offset % 12) + 1;
+            }
+        }
 
         /// <summary>
-        /// 返回农历月
+        /// 取属相字符串
         /// </summary>
-        /// <param name="month">月份</param>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
-        /// <returns>农历月</returns>
-        public static string GetLunisolarMonth(int month)
+        public string AnimalString
         {
-            if (month < 13 && month > 0)
+            get
             {
-                return months[month - 1];
+                int offset = _date.Year - AnimalStartYear; //阳历计算
+                return AnimalStr[offset % 12].ToString();
             }
-            throw new ArgumentOutOfRangeException("无效的月份!");
         }
 
         #endregion
 
-        #region 农历日
-        private static string[] days1 = { "初", "十", "廿", "三" };
+        #region 天干地支
 
         /// <summary>
-        /// 日
+        /// 取农历年的干支表示法如 乙丑年
         /// </summary>
-        private static string[] days = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
+        public string GanZhiYearString
+        {
+            get
+            {
+                int i = (_cYear - GanZhiStartYear) % 60; //计算干支
+                var tempStr = GanStr[i % 10] + ZhiStr[i % 12].ToString() + "年";
+                return tempStr;
+            }
+        }
 
         /// <summary>
-        /// 返回农历日
+        /// 取干支的月表示字符串,注意农历的闰月不记干支
         /// </summary>
-        /// <param name="day">阳历日</param>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
-        /// <returns>农历日</returns>
-        public static string GetLunisolarDay(int day)
+        public string GanZhiMonthString
         {
-            if (day > 0 && day < 32)
+            get
             {
-                if (day != 20 && day != 30)
+                //每个月的地支总是固定的,而且总是从寅月开始
+                int zhiIndex;
+                if (_cMonth > 10)
+                {
+                    zhiIndex = _cMonth - 10;
+                }
+                else
+                {
+                    zhiIndex = _cMonth + 2;
+                }
+
+                var zhi = ZhiStr[zhiIndex - 1].ToString();
+                //根据当年的干支年的干来计算月干的第一个
+                int ganIndex = 1;
+                int i = (_cYear - GanZhiStartYear) % 60; //计算干支
+                switch (i % 10)
                 {
-                    return string.Concat(days1[(day - 1) / 10], days[(day - 1) % 10]);
+                    case 0: //甲
+                        ganIndex = 3;
+                        break;
+                    case 1: //乙
+                        ganIndex = 5;
+                        break;
+                    case 2: //丙
+                        ganIndex = 7;
+                        break;
+                    case 3: //丁
+                        ganIndex = 9;
+                        break;
+                    case 4: //戊
+                        ganIndex = 1;
+                        break;
+                    case 5: //己
+                        ganIndex = 3;
+                        break;
+                    case 6: //庚
+                        ganIndex = 5;
+                        break;
+                    case 7: //辛
+                        ganIndex = 7;
+                        break;
+                    case 8: //壬
+                        ganIndex = 9;
+                        break;
+                    case 9: //癸
+                        ganIndex = 1;
+                        break;
                 }
-                return string.Concat(days[(day - 1) / 10], days1[1]);
+
+                var gan = GanStr[(ganIndex + _cMonth - 2) % 10].ToString();
+                return gan + zhi + "月";
             }
-            throw new ArgumentOutOfRangeException("无效的日!");
         }
 
+        /// <summary>
+        /// 取干支日表示法
+        /// </summary>
+        public string GanZhiDayString
+        {
+            get
+            {
+                TimeSpan ts = _date - GanZhiStartDay;
+                var offset = ts.Days;
+                var i = offset % 60;
+                return GanStr[i % 10].ToString() + ZhiStr[i % 12] + "日";
+            }
+        }
+
+        /// <summary>
+        /// 取当前日期的干支表示法如 甲子年乙丑月丙庚日
+        /// </summary>
+        public string GanZhiDateString => GanZhiYearString + GanZhiMonthString + GanZhiDayString;
+
         #endregion
+
+        /// <summary>
+        /// 取下一天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar NextDay()
+        {
+            DateTime nextDay = _date.AddDays(1);
+            return new ChineseCalendar(nextDay);
+        }
+
+        /// <summary>
+        /// 取前一天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar PervDay()
+        {
+            DateTime pervDay = _date.AddDays(-1);
+            return new ChineseCalendar(pervDay);
+        }
+
+        /// <summary>
+        /// 取下n天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar AddDays(int days)
+        {
+            DateTime nextDay = _date.AddDays(days);
+            return new ChineseCalendar(nextDay);
+        }
+
+        /// <summary>
+        /// 取下n天
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar AddWorkDays(int days)
+        {
+            var cc = new ChineseCalendar(_date);
+            while (true)
+            {
+                if (cc.IsWorkDay)
+                {
+                    days--;
+                }
+                else
+                {
+                    Console.WriteLine("阳历:" + cc.DateString);
+                    Console.WriteLine("节日:" + cc.DateHoliday);
+                    Console.WriteLine("农历节日:" + cc.ChineseCalendarHoliday);
+                    Console.WriteLine("星期:" + cc.WeekDayStr);
+                    Console.WriteLine("----------------------------");
+                }
+
+                if (days == 0)
+                {
+                    return cc;
+                }
+                cc = cc.AddDays(1);
+            }
+        }
+
+        /// <summary>
+        /// 加n月
+        /// </summary>
+        /// <returns></returns>
+        public ChineseCalendar AddMonths(int months)
+        {
+            DateTime nextDay = _date.AddMonths(months);
+            return new ChineseCalendar(nextDay);
+        }
     }
-}
+}

+ 18 - 0
Masuit.Tools/DateTimeExt/DateInfoStruct.cs

@@ -0,0 +1,18 @@
+namespace Masuit.Tools.DateTimeExt
+{
+    public struct DateInfoStruct
+    {
+        public readonly int Month;
+        public readonly int Day;
+        public readonly int Recess; //假期长度
+        public readonly string HolidayName;
+
+        public DateInfoStruct(int month, int day, int recess, string name)
+        {
+            Month = month;
+            Day = day;
+            Recess = recess;
+            HolidayName = name;
+        }
+    }
+}

+ 6 - 6
Masuit.Tools/DateTimeExt/DateTimeHelper.cs

@@ -17,7 +17,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>该年周数</returns>
         public static int GetWeekAmount(this DateTime _, int year)
         {
-            var end = new System.DateTime(year, 12, 31); //该年最后一天
+            var end = new DateTime(year, 12, 31); //该年最后一天
             var gc = new GregorianCalendar();
             return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday); //该年星期数
         }
@@ -73,7 +73,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <param name="nNumWeek">第几周</param>
         /// <param name="dtWeekStart">开始日期</param>
         /// <param name="dtWeekeEnd">结束日期</param>
-        public static void GetWeekWorkTime(this DateTime _, int nYear, int nNumWeek, out System.DateTime dtWeekStart, out System.DateTime dtWeekeEnd)
+        public static void GetWeekWorkTime(this DateTime _, int nYear, int nNumWeek, out DateTime dtWeekStart, out DateTime dtWeekeEnd)
         {
             var dt = new DateTime(nYear, 1, 1);
             dt += new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
@@ -84,10 +84,10 @@ namespace Masuit.Tools.DateTimeExt
         #region P/Invoke 设置本地时间
 
         [DllImport("kernel32.dll")]
-        private static extern bool SetLocalTime(ref SYSTEMTIME time);
+        private static extern bool SetLocalTime(ref SystemTime time);
 
         [StructLayout(LayoutKind.Sequential)]
-        private struct SYSTEMTIME
+        private struct SystemTime
         {
             public short year;
             public short month;
@@ -105,7 +105,7 @@ namespace Masuit.Tools.DateTimeExt
         /// <param name="dt">DateTime对象</param>
         public static void SetLocalTime(this DateTime dt)
         {
-            SYSTEMTIME st;
+            SystemTime st;
 
             st.year = (short)dt.Year;
             st.month = (short)dt.Month;
@@ -121,4 +121,4 @@ namespace Masuit.Tools.DateTimeExt
 
         #endregion
     }
-}
+}

+ 4 - 0
Masuit.Tools/DateTimeExt/DateUtil.cs

@@ -33,6 +33,7 @@ namespace Masuit.Tools.DateTimeExt
             {
                 return fDateTime;
             }
+
             var s = Convert.ToDateTime(fDateTime);
             return s.ToString(formatStr);
         }
@@ -156,6 +157,7 @@ namespace Masuit.Tools.DateTimeExt
                     days = 31;
                     break;
             }
+
             return days;
         }
 
@@ -247,6 +249,7 @@ namespace Masuit.Tools.DateTimeExt
                     week = "星期日";
                     break;
             }
+
             return week;
         }
 
@@ -282,6 +285,7 @@ namespace Masuit.Tools.DateTimeExt
                     week = "7";
                     break;
             }
+
             return week;
         }
 

+ 24 - 42
Masuit.Tools/DateTimeExt/TimeHelper.cs

@@ -29,8 +29,7 @@ namespace Masuit.Tools.DateTimeExt
                     break;
                 case 2:
                     firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
-                    if (DateTime.IsLeapYear(DateTime.Now.Year)) lastDay = DateTime.Now.ToString(year + "-0" + month + "-29");
-                    else lastDay = DateTime.Now.ToString(year + "-0" + month + "-28");
+                    lastDay = DateTime.IsLeapYear(DateTime.Now.Year) ? DateTime.Now.ToString(year + "-0" + month + "-29") : DateTime.Now.ToString(year + "-0" + month + "-28");
                     break;
                 case 3:
                     firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
@@ -87,12 +86,14 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns>xxxx年xx月xx日</returns>
         public static string GetFormatDate(this DateTime dt, char separator)
         {
-            if (dt != null && !dt.Equals(DBNull.Value))
+            if (dt.Equals(DBNull.Value))
             {
-                string tem = $"yyyy{separator}MM{separator}dd";
-                return dt.ToString(tem);
+                return GetFormatDate(DateTime.Now, separator);
             }
-            return GetFormatDate(DateTime.Now, separator);
+
+            string tem = $"yyyy{separator}MM{separator}dd";
+            return dt.ToString(tem);
+
         }
 
         #endregion
@@ -107,12 +108,14 @@ namespace Masuit.Tools.DateTimeExt
         /// <returns> xx时xx分xx秒 </returns>
         public static string GetFormatTime(this DateTime dt, char separator)
         {
-            if (dt != null && !dt.Equals(DBNull.Value))
+            if (dt.Equals(DBNull.Value))
             {
-                string tem = string.Format("hh{0}mm{1}ss", separator, separator);
-                return dt.ToString(tem);
+                return GetFormatDate(DateTime.Now, separator);
             }
-            return GetFormatDate(DateTime.Now, separator);
+
+            string tem = $"hh{separator}mm{separator}ss";
+            return dt.ToString(tem);
+
         }
 
         #endregion
@@ -170,34 +173,6 @@ namespace Masuit.Tools.DateTimeExt
 
         #endregion
 
-        #region 格式化日期时间
-
-        /// <summary>
-        /// 格式化日期时间
-        /// </summary>
-        /// <param name="dateTime1">日期时间</param>
-        /// <param name="dateMode">显示模式</param>
-        /// <returns>0-9种模式的日期</returns>
-        public static string FormatDate(this DateTime dateTime1, string dateMode)
-        {
-            switch (dateMode)
-            {
-                case "0": return dateTime1.ToString("yyyy-MM-dd");
-                case "1": return dateTime1.ToString("yyyy-MM-dd HH:mm:ss");
-                case "2": return dateTime1.ToString("yyyy/MM/dd");
-                case "3": return dateTime1.ToString("yyyy年MM月dd日");
-                case "4": return dateTime1.ToString("MM-dd");
-                case "5": return dateTime1.ToString("MM/dd");
-                case "6": return dateTime1.ToString("MM月dd日");
-                case "7": return dateTime1.ToString("yyyy-MM");
-                case "8": return dateTime1.ToString("yyyy/MM");
-                case "9": return dateTime1.ToString("yyyy年MM月");
-                default: return dateTime1.ToString(CultureInfo.CurrentCulture);
-            }
-        }
-
-        #endregion
-
         #region 得到随机日期
 
         /// <summary>
@@ -229,6 +204,7 @@ namespace Masuit.Tools.DateTimeExt
             {
                 return time1;
             }
+
             int maxValue = iTotalSecontds;
             if (iTotalSecontds <= int.MinValue) maxValue = int.MinValue + 1;
             int i = random.Next(Math.Abs(maxValue));
@@ -320,6 +296,7 @@ namespace Masuit.Tools.DateTimeExt
                 if (ts.Hours > 1) dateDiff = ts.Hours + "小时前";
                 else dateDiff = ts.Minutes + "分钟前";
             }
+
             return dateDiff;
         }
 
@@ -363,26 +340,31 @@ namespace Masuit.Tools.DateTimeExt
                 strResout += iTatol / iYear + "年";
                 iTatol %= iYear; //剩余
             }
+
             if (iTatol > iMonth)
             {
                 strResout += iTatol / iMonth + "月";
                 iTatol %= iMonth;
             }
+
             if (iTatol > iDay)
             {
                 strResout += iTatol / iDay + "天";
                 iTatol %= iDay;
             }
+
             if (iTatol > iHours)
             {
                 strResout += iTatol / iHours + "小时";
                 iTatol %= iHours;
             }
+
             if (iTatol > iMinutes)
             {
                 strResout += iTatol / iMinutes + "分";
                 iTatol %= iMinutes;
             }
+
             strResout += iTatol + "秒";
             return strResout;
         }
@@ -394,12 +376,12 @@ namespace Masuit.Tools.DateTimeExt
         /// <summary>
         /// C#的时间到Javascript的时间的转换
         /// </summary>
-        /// <param name="TheDate">C#的时间</param>
+        /// <param name="theDate">C#的时间</param>
         /// <returns>Javascript的时间</returns>
-        public static long CsharpTime2JavascriptTime(this DateTime TheDate)
+        public static long CsharpTime2JavascriptTime(this DateTime theDate)
         {
             DateTime d1 = new DateTime(1970, 1, 1);
-            DateTime d2 = TheDate.ToUniversalTime();
+            DateTime d2 = theDate.ToUniversalTime();
             TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
             return (long)ts.TotalMilliseconds;
         }
@@ -425,7 +407,7 @@ namespace Masuit.Tools.DateTimeExt
         public static long CsharpTime2PhpTime(this DateTime time)
         {
             DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
-                                                           //注意这里有时区问题,用now就要减掉8个小时
+            //注意这里有时区问题,用now就要减掉8个小时
             return (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000;
         }
 

+ 18 - 0
Masuit.Tools/DateTimeExt/WeekHolidayStruct.cs

@@ -0,0 +1,18 @@
+namespace Masuit.Tools.DateTimeExt
+{
+    public struct WeekHolidayStruct
+    {
+        public readonly int Month;
+        public readonly int WeekAtMonth;
+        public readonly int WeekDay;
+        public readonly string HolidayName;
+
+        public WeekHolidayStruct(int month, int weekAtMonth, int weekDay, string name)
+        {
+            Month = month;
+            WeekAtMonth = weekAtMonth;
+            WeekDay = weekDay;
+            HolidayName = name;
+        }
+    }
+}

+ 1 - 5
Masuit.Tools/ExpressionGenericMapper.cs

@@ -43,11 +43,7 @@ namespace Masuit.Tools
                 func = lambda.Compile();
             }
 
-            if (source == null)
-            {
-                return default(TDestination);
-            }
-            return ((Func<TSource, TDestination>)func)(source); //拼装是一次性的
+            return source == null ? default(TDestination) : ((Func<TSource, TDestination>)func)(source);
         }
 
         /// <summary>

+ 54 - 16
Masuit.Tools/Extensions.cs

@@ -257,7 +257,10 @@ namespace Masuit.Tools
         public static TDestination MapTo<TDestination>(this object source) where TDestination : new()
         {
             TDestination dest = new TDestination();
-            dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source)); });
+            dest.GetType().GetProperties().ForEach(p =>
+            {
+                p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
+            });
             return dest;
         }
 
@@ -272,7 +275,10 @@ namespace Masuit.Tools
             return await Task.Run(() =>
             {
                 TDestination dest = new TDestination();
-                dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source)); });
+                dest.GetType().GetProperties().ForEach(p =>
+                {
+                    p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
+                });
                 return dest;
             });
         }
@@ -302,7 +308,10 @@ namespace Masuit.Tools
         public static T Copy<T>(this T source) where T : new()
         {
             T dest = new T();
-            dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source)); });
+            dest.GetType().GetProperties().ForEach(p =>
+            {
+                p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
+            });
             return dest;
         }
 
@@ -315,7 +324,10 @@ namespace Masuit.Tools
         /// <returns></returns>
         public static T CopyTo<T>(this T source, T dest) where T : new()
         {
-            dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source)); });
+            dest.GetType().GetProperties().ForEach(p =>
+            {
+                p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
+            });
             return dest;
         }
 
@@ -325,13 +337,15 @@ namespace Masuit.Tools
         /// <typeparam name="T"></typeparam>
         /// <param name="source"></param>
         /// <returns></returns>
-        public static async Task<T> CopyAsync<T>(this T source) where T : new() =>
-            await Task.Run(() =>
+        public static async Task<T> CopyAsync<T>(this T source) where T : new() => await Task.Run(() =>
+        {
+            T dest = new T();
+            dest.GetType().GetProperties().ForEach(p =>
             {
-                T dest = new T();
-                dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source)); });
-                return dest;
+                p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
             });
+            return dest;
+        });
 
         /// <summary>
         /// 映射到目标类型的集合
@@ -344,7 +358,10 @@ namespace Masuit.Tools
             foreach (var o in source)
             {
                 var dest = new TDestination();
-                dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o)); });
+                dest.GetType().GetProperties().ForEach(p =>
+                {
+                    p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
+                });
                 yield return dest;
             }
         }
@@ -363,7 +380,10 @@ namespace Masuit.Tools
                 foreach (var o in source)
                 {
                     var dest = new TDestination();
-                    dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o)); });
+                    dest.GetType().GetProperties().ForEach(p =>
+                    {
+                        p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
+                    });
                     list.Add(dest);
                 }
 
@@ -382,7 +402,10 @@ namespace Masuit.Tools
             foreach (var o in source)
             {
                 var dest = new TDestination();
-                dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o)); });
+                dest.GetType().GetProperties().ForEach(p =>
+                {
+                    p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
+                });
                 yield return dest;
             }
         }
@@ -401,7 +424,10 @@ namespace Masuit.Tools
                 foreach (var o in source)
                 {
                     var dest = new TDestination();
-                    dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o)); });
+                    dest.GetType().GetProperties().ForEach(p =>
+                    {
+                        p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
+                    });
                     list.Add(dest);
                 }
 
@@ -420,7 +446,10 @@ namespace Masuit.Tools
             foreach (var o in source)
             {
                 var dest = new TDestination();
-                dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o)); });
+                dest.GetType().GetProperties().ForEach(p =>
+                {
+                    p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
+                });
                 yield return dest;
             }
         }
@@ -439,7 +468,10 @@ namespace Masuit.Tools
                 foreach (var o in source)
                 {
                     var dest = new TDestination();
-                    dest.GetType().GetProperties().ForEach(p => { p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o)); });
+                    dest.GetType().GetProperties().ForEach(p =>
+                    {
+                        p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
+                    });
                     list.Add(dest);
                 }
 
@@ -454,7 +486,10 @@ namespace Masuit.Tools
         /// </summary>
         /// <param name="source"></param>
         /// <returns></returns>
-        public static string ToJsonString(this object source) => JsonConvert.SerializeObject(source, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
+        public static string ToJsonString(this object source) => JsonConvert.SerializeObject(source, new JsonSerializerSettings()
+        {
+            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
+        });
 
         /// <summary>
         /// 转换成json字符串
@@ -1497,8 +1532,10 @@ namespace Masuit.Tools
                 {
                     length = 5;
                 }
+
                 temp = temp.Substring(0, length);
             }
+
             return Regex.Replace(temp, @"\p{P}|\+", string.Empty);
         }
 
@@ -1545,6 +1582,7 @@ namespace Masuit.Tools
                 uint current = uint.Parse(inputs[0]) << 24 | uint.Parse(inputs[1]) << 16 | uint.Parse(inputs[2]) << 8 | uint.Parse(inputs[3]);
                 return current >= start && current <= end;
             }
+
             return false;
         }
     }

+ 22 - 3
Masuit.Tools/Files/Compress.cs

@@ -23,7 +23,10 @@ namespace Masuit.Tools.Files
         /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
         public static void PackFiles(string filename, string directory)
         {
-            FastZip fz = new FastZip { CreateEmptyDirectories = true };
+            FastZip fz = new FastZip
+            {
+                CreateEmptyDirectories = true
+            };
             fz.CreateZip(filename, directory, true, "");
         }
 
@@ -34,7 +37,10 @@ namespace Masuit.Tools.Files
         /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
         public static async void PackFilesAsync(string filename, string directory)
         {
-            FastZip fz = new FastZip { CreateEmptyDirectories = true };
+            FastZip fz = new FastZip
+            {
+                CreateEmptyDirectories = true
+            };
             await Task.Run(() =>
             {
                 fz.CreateZip(filename, directory, true, "");
@@ -81,6 +87,7 @@ namespace Masuit.Tools.Files
                     }
                 }
             }
+
             return true;
         }
 
@@ -122,6 +129,7 @@ namespace Masuit.Tools.Files
                     }
                 }).ConfigureAwait(false);
             }
+
             return true;
         }
 
@@ -171,6 +179,7 @@ namespace Masuit.Tools.Files
                     GetFilesRecurs(directory);
                 }
             }
+
             MemoryStream ms = new MemoryStream();
             byte[] buffer;
             using (ZipFile f = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))
@@ -193,15 +202,21 @@ namespace Masuit.Tools.Files
                 {
                     dirname = Directory.GetParent(fileList[0]).FullName;
                 }
+
                 f.NameTransform = new ZipNameTransform(dirname); //通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。  
-                fileList.ForEach(s => { f.Add(s); });
+                fileList.ForEach(s =>
+                {
+                    f.Add(s);
+                });
                 f.CommitUpdate();
                 buffer = new byte[ms.Length];
                 ms.Position = 0;
                 ms.Read(buffer, 0, buffer.Length);
             }
+
             return buffer;
         }
+
         #endregion
 
         #region 解压
@@ -230,6 +245,7 @@ namespace Masuit.Tools.Files
                             Directory.CreateDirectory(fileName);
                             continue;
                         }
+
                         using (FileStream streamWriter = File.Create(fileName))
                         {
                             byte[] data = new byte[2048];
@@ -284,6 +300,7 @@ namespace Masuit.Tools.Files
                     s.Write(buffer, 0, buffer.Length);
                 }
             }
+
             var folders = Directory.GetDirectories(folderToZip);
             foreach (string folder in folders)
             {
@@ -315,6 +332,7 @@ namespace Masuit.Tools.Files
                 res = ZipFileDictory(folderToZip, s, "");
                 s.Finish();
             }
+
             return res;
         }
 
@@ -347,6 +365,7 @@ namespace Masuit.Tools.Files
                     zipStream.Write(buffer, 0, buffer.Length);
                 }
             }
+
             return true;
         }
 

+ 9 - 7
Masuit.Tools/Files/ExtensionAttach.cs

@@ -1,7 +1,7 @@
-using System;
+using Microsoft.Win32;
+using System;
 using System.IO;
 using System.Security;
-using Microsoft.Win32;
 
 namespace Masuit.Tools.Files
 {
@@ -20,28 +20,29 @@ namespace Masuit.Tools.Files
         /// <exception cref="IOException">The nesting level exceeds 510.-or-A system error occurred, such as deletion of the key, or an attempt to create a key in the <see cref="F:Microsoft.Win32.Registry.LocalMachine" /> root.</exception>
         public static void SaveReg(string filePathString, string pFileTypeName)
         {
-            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey("", true);              //打开注册表
+            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey("", true); //打开注册表
             RegistryKey vrPkey = regKey?.OpenSubKey(pFileTypeName, true);
             if (vrPkey != null)
             {
                 regKey.DeleteSubKey(pFileTypeName, true);
             }
+
             regKey?.CreateSubKey(pFileTypeName);
             vrPkey = regKey?.OpenSubKey(pFileTypeName, true);
             vrPkey?.SetValue("", "Exec");
             vrPkey = regKey?.OpenSubKey("Exec", true);
-            if (vrPkey != null) regKey.DeleteSubKeyTree("Exec");         //如果等于空就删除注册表DSKJIVR
+            if (vrPkey != null) regKey.DeleteSubKeyTree("Exec"); //如果等于空就删除注册表DSKJIVR
 
             regKey?.CreateSubKey("Exec");
             vrPkey = regKey?.OpenSubKey("Exec", true);
             vrPkey?.CreateSubKey("shell");
-            vrPkey = vrPkey?.OpenSubKey("shell", true);                      //写入必须路径
+            vrPkey = vrPkey?.OpenSubKey("shell", true); //写入必须路径
             vrPkey?.CreateSubKey("open");
             vrPkey = vrPkey?.OpenSubKey("open", true);
             vrPkey?.CreateSubKey("command");
             vrPkey = vrPkey?.OpenSubKey("command", true);
             string pathString = "\"" + filePathString + "\" \"%1\"";
-            vrPkey?.SetValue("", pathString);                                    //写入数据
+            vrPkey?.SetValue("", pathString); //写入数据
         }
 
         /// <summary>
@@ -59,10 +60,11 @@ namespace Masuit.Tools.Files
             {
                 regkey.DeleteSubKey(pFileTypeName, true);
             }
+
             if (vrPkey != null)
             {
                 regkey.DeleteSubKeyTree("Exec");
             }
         }
     }
-}
+}

+ 6 - 1
Masuit.Tools/Files/FileExt.cs

@@ -118,6 +118,7 @@ namespace Masuit.Tools.Files
             {
                 throw new ArgumentNullException("algName 不能为 null");
             }
+
             if (string.Compare(algName, "sha1", true) == 0)
             {
                 algorithm = System.Security.Cryptography.SHA1.Create();
@@ -128,8 +129,10 @@ namespace Masuit.Tools.Files
                 {
                     throw new Exception("algName 只能使用 sha1 或 md5");
                 }
+
                 algorithm = System.Security.Cryptography.MD5.Create();
             }
+
             return algorithm.ComputeHash(stream);
         }
 
@@ -146,6 +149,7 @@ namespace Masuit.Tools.Files
             {
                 throw new ArgumentNullException("algName 不能为 null");
             }
+
             if (string.Compare(algName, "sha1", true) == 0)
             {
                 algorithm = System.Security.Cryptography.SHA1.Create();
@@ -156,10 +160,11 @@ namespace Masuit.Tools.Files
                 {
                     throw new Exception("algName 只能使用 sha1 或 md5");
                 }
+
                 algorithm = System.Security.Cryptography.MD5.Create();
             }
-            return await Task.Run(() => algorithm.ComputeHash(stream)).ConfigureAwait(false);
 
+            return await Task.Run(() => algorithm.ComputeHash(stream)).ConfigureAwait(false);
         }
 
         /// <summary>

+ 1 - 1
Masuit.Tools/Files/INIFile.cs

@@ -86,4 +86,4 @@ namespace Masuit.Tools.Files
             IniWriteValue(Section, null, null);
         }
     }
-}
+}

+ 43 - 18
Masuit.Tools/Hardware/SystemInfo.cs

@@ -1,4 +1,6 @@
-using System;
+using Masuit.Tools.Logging;
+using Microsoft.Win32;
+using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -8,8 +10,6 @@ using System.Runtime.InteropServices;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading;
-using Masuit.Tools.Logging;
-using Microsoft.Win32;
 
 namespace Masuit.Tools.Hardware
 {
@@ -122,6 +122,7 @@ namespace Masuit.Tools.Hardware
                         var mo = (ManagementObject)o;
                         if (mo["FreePhysicalMemory"] != null) availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
                     }
+
                     return availablebytes;
                 }
                 catch (Exception)
@@ -168,6 +169,7 @@ namespace Masuit.Tools.Hardware
                     string strTitle = sb.ToString();
                     if (!string.IsNullOrEmpty(strTitle)) apps.Add(strTitle);
                 }
+
                 hwCurr = GetWindow(hwCurr, GwHwndnext);
             }
 
@@ -272,6 +274,7 @@ namespace Masuit.Tools.Hardware
                 {
                     str += managementObject.Properties["CurrentTemperature"].Value.ToString();
                 }
+
                 //这就是CPU的温度了
                 double temp = (double.Parse(str) - 2732) / 10;
                 return Math.Round(temp, 2);
@@ -306,9 +309,8 @@ namespace Masuit.Tools.Hardware
         /// <returns></returns>
         public static string GetMemoryVData()
         {
-            string str;
             double d = GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
-            str = d.ToString("F") + "% (";
+            var str = d.ToString("F") + "% (";
 
             d = GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
             str += FormatBytes(d) + " / ";
@@ -334,6 +336,7 @@ namespace Masuit.Tools.Hardware
         {
             return GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
         }
+
         /// <summary>
         /// 获取虚拟内存总大小
         /// </summary>
@@ -450,6 +453,7 @@ namespace Masuit.Tools.Hardware
                         }
                     }
                 }
+
                 return list;
             }
             catch (Exception)
@@ -468,7 +472,6 @@ namespace Masuit.Tools.Hardware
             try
             {
                 IList<string> list = new List<string>();
-                var st = "";
                 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                 using (mc)
                 {
@@ -479,19 +482,22 @@ namespace Masuit.Tools.Hardware
                         {
                             if ((bool)mo["IPEnabled"])
                             {
-                                st = mo["IpAddress"].ToString();
                                 var ar = (Array)(mo.Properties["IpAddress"].Value);
-                                st = ar.GetValue(0).ToString();
+                                var st = ar.GetValue(0).ToString();
                                 list.Add(st);
                             }
                         }
+
                         return list;
                     }
                 }
             }
             catch (Exception)
             {
-                return new List<string>() { "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" };
+                return new List<string>()
+                {
+                    "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。"
+                };
             }
         }
 
@@ -507,6 +513,7 @@ namespace Masuit.Tools.Hardware
             {
                 return m.Groups[2].Value;
             }
+
             try
             {
                 System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
@@ -539,7 +546,8 @@ namespace Masuit.Tools.Hardware
 
                 Process proc = new Process
                 {
-                    StartInfo = {
+                    StartInfo =
+                    {
                         FileName = filename,
                         CreateNoWindow = true,
                         Arguments = arguments,
@@ -551,12 +559,14 @@ namespace Masuit.Tools.Hardware
 
                 using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
                 {
-                    Thread.Sleep(100);           //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                                                 //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                    if (!proc.HasExited)         //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                    {                            //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
+                    Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
+                    //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
+                    if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
+                    {
+                        //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
                         proc.Kill();
                     }
+
                     string txt = sr.ReadToEnd();
                     sr.Close();
                     if (recordLog)
@@ -586,6 +596,7 @@ namespace Masuit.Tools.Hardware
                 return "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。";
             }
         }
+
         #region 将速度值格式化成字节单位
 
         /// <summary>
@@ -601,6 +612,7 @@ namespace Masuit.Tools.Hardware
                 bytes /= 1024;
                 ++unit;
             }
+
             string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " ";
             return s + (Unit)unit;
         }
@@ -622,6 +634,7 @@ namespace Masuit.Tools.Hardware
             {
                 return ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
             }
+
             return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & Int32.MaxValue);
         }
 
@@ -682,11 +695,15 @@ namespace Masuit.Tools.Hardware
                         }
                     }
                 }
+
                 return dic;
             }
             catch (Exception)
             {
-                return new Dictionary<string, string>() { { "null", "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" } };
+                return new Dictionary<string, string>()
+                {
+                    { "null", "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
+                };
             }
         }
 
@@ -712,6 +729,7 @@ namespace Masuit.Tools.Hardware
                         }
                     }
                 }
+
                 return dic;
             }
             catch (Exception)
@@ -744,11 +762,15 @@ namespace Masuit.Tools.Hardware
                         }
                     }
                 }
+
                 return dic;
             }
             catch (Exception)
             {
-                return new Dictionary<string, string>() { { "null", "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" } };
+                return new Dictionary<string, string>()
+                {
+                    { "null", "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
+                };
             }
         }
 
@@ -775,11 +797,15 @@ namespace Masuit.Tools.Hardware
                         }
                     }
                 }
+
                 return dic;
             }
             catch (Exception)
             {
-                return new Dictionary<string, double>() { { "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 } };
+                return new Dictionary<string, double>()
+                {
+                    { "未能获取到操作系统版本,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 }
+                };
             }
         }
 
@@ -815,7 +841,6 @@ namespace Masuit.Tools.Hardware
         public static extern uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
 
         [DllImport("User32")]
-        // ReSharper disable once MissingXmlDoc
         public static extern int GetWindow(int hWnd, int wCmd);
 
         [DllImport("User32")]

+ 132 - 322
Masuit.Tools/Html/HtmlHelper.cs

@@ -3,9 +3,9 @@ using System;
 using System.IO;
 using System.IO.Compression;
 using System.Net;
+using System.Net.Http;
 using System.Text;
 using System.Text.RegularExpressions;
-using System.Threading;
 using System.Web;
 
 namespace Masuit.Tools.Html
@@ -41,28 +41,16 @@ namespace Masuit.Tools.Html
     public static partial class HtmlTools
     {
         #region 私有字段
-        private static CookieContainer cc = new CookieContainer();
+
         private static string contentType = "application/x-www-form-urlencoded";
-        private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg," +
-                                       " application/x-shockwave-flash, application/x-silverlight, " +
-                                       "application/vnd.ms-excel, application/vnd.ms-powerpoint, " +
-                                       "application/msword, application/x-ms-application," +
-                                       " application/x-ms-xbap," +
-                                       " application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
-        private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;" +
-                                          " .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
+        private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg," + " application/x-shockwave-flash, application/x-silverlight, " + "application/vnd.ms-excel, application/vnd.ms-powerpoint, " + "application/msword, application/x-ms-application," + " application/x-ms-xbap," + " application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
+        private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;" + " .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
         private static int delay = 1000;
-        private static int currentTry = 0;
+        private static int currentTry;
+
         #endregion
 
         #region 公有属性
-        /// <summary> 
-        /// Cookie容器
-        /// </summary> 
-        public static CookieContainer CookieContainer
-        {
-            get { return cc; }
-        }
 
         /// <summary> 
         /// 获取网页源码时使用的编码
@@ -80,13 +68,17 @@ namespace Masuit.Tools.Html
                 return r.Next(delay, delay * 2);
                 // return (r.Next(delay / 1000, delay / 1000 * 2)) * 1000;
             }
-            set { delay = value; }
+            set
+            {
+                delay = value;
+            }
         }
 
         /// <summary>
         /// 最大尝试次数
         /// </summary>
         public static int MaxTry { get; set; } = 300;
+
         #endregion
 
         #region 1、获取HTML
@@ -105,123 +97,34 @@ namespace Masuit.Tools.Html
             {
                 return strText.Substring(0, length);
             }
+
             return strText;
         }
 
         /// <summary>
-        /// 获取指定页面的HTML代码
+        /// 获取HTML
         /// </summary>
         /// <param name="_"></param>
-        /// <param name="url">指定页面的路径</param>
-        /// <param name="postData">post 提交的字符串</param>
-        /// <param name="isPost">是否以post方式发送请求</param>
-        /// <param name="cookieContainer">Cookie集合</param>
-        public static string GetHtml(this HttpWebRequest _, string url, string postData, bool isPost, CookieContainer cookieContainer)
+        /// <param name="url">地址</param>
+        public static string GetHtml(this HttpClient _, string url)
         {
-            if (string.IsNullOrEmpty(postData))
+            return _.GetAsync(url).ContinueWith(task =>
             {
-                return GetHtml(null, url, cookieContainer);
-            }
-            Thread.Sleep(NetworkDelay);
-            currentTry++;
-            HttpWebRequest httpWebRequest = null;
-            HttpWebResponse httpWebResponse = null;
-            try
-            {
-                byte[] byteRequest = Encoding.Default.GetBytes(postData);
-
-                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
-                httpWebRequest.CookieContainer = cookieContainer;
-                httpWebRequest.ContentType = contentType;
-                httpWebRequest.ServicePoint.ConnectionLimit = MaxTry;
-                httpWebRequest.Referer = url;
-                httpWebRequest.Accept = accept;
-                httpWebRequest.UserAgent = userAgent;
-                httpWebRequest.Method = isPost ? "POST" : "GET";
-                httpWebRequest.ContentLength = byteRequest.Length;
-
-                httpWebRequest.AllowAutoRedirect = false;
-
-                Stream stream = httpWebRequest.GetRequestStream();
-                stream.Write(byteRequest, 0, byteRequest.Length);
-                stream.Close();
-
-                try
-                {
-                    httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-                    //redirectURL = httpWebResponse.Headers["Location"];// Get redirected uri
-                }
-                catch (WebException ex)
+                if (task.IsCanceled || task.IsFaulted)
                 {
-                    httpWebResponse = (HttpWebResponse)ex.Response;
+                    return string.Empty;
                 }
-                //httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-
-                Stream responseStream = httpWebResponse.GetResponseStream();
-                StreamReader streamReader = new StreamReader(responseStream, Encoding);
-                string html = streamReader.ReadToEnd();
-                streamReader.Close();
-                responseStream.Close();
-                currentTry = 0;
-                httpWebRequest.Abort();
-                httpWebResponse.Close();
-                return html;
-            }
-            catch (Exception)
-            {
-                if (currentTry <= MaxTry)
+
+                var resp = task.Result;
+                if (resp.IsSuccessStatusCode)
                 {
-                    GetHtml(null, url, postData, isPost, cookieContainer);
+                    return resp.Content.ReadAsStringAsync().Result;
                 }
-                currentTry--;
-                if (httpWebRequest != null) httpWebRequest.Abort();
-                if (httpWebResponse != null) httpWebResponse.Close();
-                return string.Empty;
-            }
-        }
 
-        /// <summary>
-        /// 获取HTML
-        /// </summary>
-        /// <param name="_"></param>
-        /// <param name="url">地址</param>
-        /// <param name="cookieContainer">Cookie集合</param>
-        public static string GetHtml(this HttpWebRequest _, string url, CookieContainer cookieContainer)
-        {
-            Thread.Sleep(NetworkDelay);
-            currentTry++;
-            HttpWebRequest httpWebRequest = null;
-            HttpWebResponse httpWebResponse = null;
-            try
-            {
-                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
-                httpWebRequest.CookieContainer = cookieContainer;
-                httpWebRequest.ContentType = contentType;
-                httpWebRequest.ServicePoint.ConnectionLimit = MaxTry;
-                httpWebRequest.Referer = url;
-                httpWebRequest.Accept = accept;
-                httpWebRequest.UserAgent = userAgent;
-                httpWebRequest.Method = "GET";
-                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-                Stream responseStream = httpWebResponse.GetResponseStream();
-                StreamReader streamReader = new StreamReader(responseStream, Encoding);
-                string html = streamReader.ReadToEnd();
-                streamReader.Close();
-                responseStream.Close();
-                currentTry--;
-                httpWebRequest.Abort();
-                httpWebResponse.Close();
-                return html;
-            }
-            catch (Exception)
-            {
-                if (currentTry <= MaxTry) GetHtml(null, url, cookieContainer);
-                currentTry--;
-                if (httpWebRequest != null) httpWebRequest.Abort();
-                if (httpWebResponse != null) httpWebResponse.Close();
                 return string.Empty;
-            }
+            }).Result;
         }
+
         #endregion
 
         #region 2、获取字符流
@@ -237,50 +140,25 @@ namespace Masuit.Tools.Html
         /// ---------------------------------------------------------------------------------------------------------------
         /// <param name="_"></param>
         /// <param name="url">地址</param>
-        ///  <param name="cookieContainer">cookieContainer</param>
-        public static Stream GetStream(this HttpWebRequest _, string url, CookieContainer cookieContainer)
+        public static Stream GetStream(this HttpClient _, string url)
         {
-            currentTry++;
-
-            HttpWebRequest httpWebRequest = null;
-            HttpWebResponse httpWebResponse = null;
-
-            try
-            {
-                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
-                httpWebRequest.CookieContainer = cookieContainer;
-                httpWebRequest.ContentType = contentType;
-                httpWebRequest.ServicePoint.ConnectionLimit = MaxTry;
-                httpWebRequest.Referer = url;
-                httpWebRequest.Accept = accept;
-                httpWebRequest.UserAgent = userAgent;
-                httpWebRequest.Method = "GET";
-
-                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
-                Stream responseStream = httpWebResponse.GetResponseStream();
-                currentTry--;
-                return responseStream;
-            }
-            catch (Exception)
+            return _.GetAsync(url).ContinueWith(task =>
             {
-                if (currentTry <= MaxTry)
+                if (task.IsCanceled || task.IsFaulted)
                 {
-                    GetHtml(null, url, cookieContainer);
+                    return null;
                 }
 
-                currentTry--;
-
-                if (httpWebRequest != null)
-                {
-                    httpWebRequest.Abort();
-                }
-                if (httpWebResponse != null)
+                var resp = task.Result;
+                if (resp.IsSuccessStatusCode)
                 {
-                    httpWebResponse.Close();
+                    return resp.Content.ReadAsStreamAsync().Result;
                 }
+
                 return null;
-            }
+            }).Result;
         }
+
         #endregion
 
         #region 3、清除HTML标记
@@ -293,9 +171,9 @@ namespace Masuit.Tools.Html
         public static string ClearHtml(this string html)
         {
             string s = Regex.Match(Regex.Replace(html, @"background-color:#?\w{3,7}|font-family:'?[\w|\(|\)]*'?;?", string.Empty), @"<body[^>]*>([\s\S]*)<\/body>").Groups[1].Value.Replace("&#xa0;", string.Empty);
-            s = Regex.Replace(s, @"\w+-?\w+:0\w+;?", string.Empty);//去除多余的零值属性
-            s = Regex.Replace(s, "alt=\"(.+?)\"", string.Empty);//除去alt属性
-            s = Regex.Replace(s, @"-aw.+?\s", string.Empty);//去除Word产生的-aw属性
+            s = Regex.Replace(s, @"\w+-?\w+:0\w+;?", string.Empty); //去除多余的零值属性
+            s = Regex.Replace(s, "alt=\"(.+?)\"", string.Empty); //除去alt属性
+            s = Regex.Replace(s, @"-aw.+?\s", string.Empty); //去除Word产生的-aw属性
             return s;
         }
 
@@ -307,25 +185,24 @@ namespace Masuit.Tools.Html
         public static string RemoveHtml(this string htmlstring)
         {
             //删除脚本   
-            htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
 
             //删除HTML   
             Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
             htmlstring = regex.Replace(htmlstring, "");
-            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "<(.[^>]*)>", "", RegexOptions.IgnoreCase);
             htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
-
-            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
-            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "-->", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "<!--.*", "", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(quot|#34);", "\"", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(amp|#38);", "&", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(lt|#60);", "<", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(gt|#62);", ">", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
+            htmlstring = Regex.Replace(htmlstring, "&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
             htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
 
             htmlstring.Replace("<", "");
@@ -338,7 +215,9 @@ namespace Masuit.Tools.Html
         #endregion
 
         #region 4、匹配页面的链接
+
         #region 4.1获取页面的链接正则
+
         /// <summary>
         /// 4.1获取页面的链接正则
         /// </summary>
@@ -351,11 +230,14 @@ namespace Masuit.Tools.Html
             {
                 MatchVale += (m.Value).ToLower().Replace("href=", "").Trim() + "|";
             }
+
             return MatchVale;
         }
+
         #endregion
 
         #region  4.2取得所有链接URL
+
         /// <summary>
         /// 4.2取得所有链接URL
         /// </summary>
@@ -370,11 +252,14 @@ namespace Masuit.Tools.Html
                 sb.AppendLine(m.Result("$1"));
                 m.NextMatch();
             }
+
             return sb.ToString();
         }
+
         #endregion
 
         #region 4.3获取所有连接文本
+
         /// <summary>
         /// 4.3获取所有连接文本
         /// </summary>
@@ -393,7 +278,9 @@ namespace Masuit.Tools.Html
 
             return sb.ToString();
         }
+
         #endregion
+
         #endregion
 
         #region  5、匹配页面的图片地址
@@ -406,22 +293,6 @@ namespace Masuit.Tools.Html
         /// <returns></returns>
         public static string ReplaceHtmlImgSource(this string html, string imgDest) => html.Replace("<img src=\"", "<img src=\"" + imgDest + "/");
 
-        /// <summary>
-        /// 匹配页面的图片地址
-        /// </summary>
-        /// <param name="htmlCode">html代码</param>
-        /// <param name="imgHttp">要补充的http://路径信息</param>
-        public static string GetImgSrc(this string htmlCode, string imgHttp)
-        {
-            string matchVale = "";
-            string Reg = @"<img.+?>";
-            foreach (Match m in Regex.Matches(htmlCode.ToLower(), Reg))
-            {
-                matchVale += GetImg((m.Value).ToLower().Trim(), imgHttp) + "|";
-            }
-            return matchVale;
-        }
-
         /// <summary>
         /// 将src的绝对路径换成相对路径
         /// </summary>
@@ -461,6 +332,7 @@ namespace Masuit.Tools.Html
             {
                 src = src.Substring(0, index);
             }
+
             return src;
         }
 
@@ -480,30 +352,13 @@ namespace Masuit.Tools.Html
                 {
                     src = src.Substring(0, index);
                 }
+
                 return src;
             }
+
             return string.Empty;
         }
 
-        /// <summary>
-        /// 匹配<img src="" />中的图片路径实际链接
-        /// </summary>
-        /// <param name="imgString"><img src="" />字符串</param>
-        /// <param name="imgHttp">图片路径</param>
-        public static string GetImg(this string imgString, string imgHttp)
-        {
-            string matchVale = "";
-            string Reg = @"src=.+\.(bmp|jpg|gif|png|)";
-            foreach (Match m in Regex.Matches(imgString.ToLower(), Reg))
-            {
-                matchVale += (m.Value).ToLower().Trim().Replace("src=", "");
-            }
-            if (matchVale.IndexOf(".net") != -1 || matchVale.IndexOf(".com") != -1 || matchVale.IndexOf(".org") != -1 || matchVale.IndexOf(".cn") != -1 || matchVale.IndexOf(".cc") != -1 || matchVale.IndexOf(".info") != -1 || matchVale.IndexOf(".biz") != -1 || matchVale.IndexOf(".tv") != -1)
-            {
-                return matchVale;
-            }
-            return imgHttp + matchVale;
-        }
         #endregion
 
         #region 6、抓取远程页面内容
@@ -528,6 +383,7 @@ namespace Masuit.Tools.Html
                 {
                     sb.Append(sr.ReadLine() + "\r\n");
                 }
+
                 strResult = sb.ToString();
                 hwrs.Close();
             }
@@ -535,6 +391,7 @@ namespace Masuit.Tools.Html
             {
                 strResult = ee.Message;
             }
+
             return strResult;
         }
 
@@ -567,25 +424,30 @@ namespace Masuit.Tools.Html
             {
                 strResult = ex.Message;
             }
+
             return strResult;
         }
+
         #endregion
 
         #region 7、压缩HTML输出
+
         /// <summary>
         /// 7.1压缩HTML输出
         /// </summary>
         /// <param name="html">html</param>
         public static string ZipHtml(this string html)
         {
-            html = Regex.Replace(html, @">\s+?<", "><");//去除HTML中的空白字符
+            html = Regex.Replace(html, @">\s+?<", "><"); //去除HTML中的空白字符
             html = Regex.Replace(html, @"\r\n\s*", "");
             html = Regex.Replace(html, @"<body([\s|\S]*?)>([\s|\S]*?)</body>", @"<body$1>$2</body>", RegexOptions.IgnoreCase);
             return html;
         }
+
         #endregion
 
         #region 8、过滤HTML标签
+
         #region 8.1过滤指定HTML标签
 
         /// <summary>
@@ -601,9 +463,12 @@ namespace Masuit.Tools.Html
                 rStr = Regex.Replace(sTextStr, "<" + htmlStr + "[^>]*>", "", RegexOptions.IgnoreCase);
                 rStr = Regex.Replace(rStr, "</" + htmlStr + ">", "", RegexOptions.IgnoreCase);
             }
+
             return rStr;
         }
+
         #endregion
+
         #region 8.2过滤HTML中的不安全标签
 
         /// <summary>
@@ -617,12 +482,15 @@ namespace Masuit.Tools.Html
             content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
             return content;
         }
+
         #endregion
+
         #endregion
 
         #region 转换HTML操作
 
         #region HTML转行成TEXT
+
         /// <summary>
         /// HTML转行成TEXT HtmlToTxt(string strHtml)
         /// </summary>
@@ -630,38 +498,42 @@ namespace Masuit.Tools.Html
         /// <returns>普通文本</returns>
         public static string HtmlToTxt(this string strHtml)
         {
-            string[] aryReg ={
-            @"<script[^>]*?>.*?</script>",
-            @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
-            @"([\r\n])[\s]+",
-            @"&(quot|#34);",
-            @"&(amp|#38);",
-            @"&(lt|#60);",
-            @"&(gt|#62);",
-            @"&(nbsp|#160);",
-            @"&(iexcl|#161);",
-            @"&(cent|#162);",
-            @"&(pound|#163);",
-            @"&(copy|#169);",
-            @"&#(\d+);",
-            @"-->",
-            @"<!--.*\n"
+            string[] aryReg =
+            {
+                @"<script[^>]*?>.*?</script>",
+                @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
+                @"([\r\n])[\s]+",
+                @"&(quot|#34);",
+                @"&(amp|#38);",
+                @"&(lt|#60);",
+                @"&(gt|#62);",
+                @"&(nbsp|#160);",
+                @"&(iexcl|#161);",
+                @"&(cent|#162);",
+                @"&(pound|#163);",
+                @"&(copy|#169);",
+                @"&#(\d+);",
+                @"-->",
+                @"<!--.*\n"
             };
 
             string strOutput = strHtml;
-            for (int i = 0; i < aryReg.Length; i++)
+            foreach (var t in aryReg)
             {
-                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
+                Regex regex = new Regex(t, RegexOptions.IgnoreCase);
                 strOutput = regex.Replace(strOutput, string.Empty);
             }
+
             strOutput.Replace("<", "");
             strOutput.Replace(">", "");
             strOutput.Replace("\r\n", "");
             return strOutput;
         }
+
         #endregion
 
         #region 字符串转换为 Html
+
         /// <summary>
         /// 字符串转换为 HtmlStringToHtml(string str)
         /// </summary>
@@ -680,9 +552,11 @@ namespace Masuit.Tools.Html
             str = str.Replace("\r\n", "<br />");
             return str;
         }
+
         #endregion
 
         #region Html转换成字符串
+
         /// <summary>
         /// html转换成字符串
         /// </summary>
@@ -700,7 +574,9 @@ namespace Masuit.Tools.Html
             strHtml = Regex.Replace(strHtml, @"<\/?[^>]+>", "", RegexOptions.IgnoreCase);
             return strHtml;
         }
+
         #endregion
+
         #endregion
 
         #region 获取URL编码
@@ -713,103 +589,38 @@ namespace Masuit.Tools.Html
         /// <returns>编码类型</returns>
         public static string GetEncoding(this HttpWebRequest _, string url)
         {
-            HttpWebRequest request = null;
-            HttpWebResponse response = null;
-            StreamReader reader = null;
-            try
-            {
-                request = (HttpWebRequest)WebRequest.Create(url);
-                request.Timeout = 20000;
-                request.AllowAutoRedirect = false;
-                response = (HttpWebResponse)request.GetResponse();
-                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
-                {
-                    if (response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
-                    {
-                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
-                    }
-                    else
-                    {
-                        reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
-                    }
-
-                    string html = reader.ReadToEnd();
-                    Regex regCharset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
-                    if (regCharset.IsMatch(html))
-                    {
-                        return regCharset.Match(html).Groups["charset"].Value;
-                    }
-                    else if (response.CharacterSet != string.Empty)
-                    {
-                        return response.CharacterSet;
-                    }
-                    else
-                    {
-                        return Encoding.Default.BodyName;
-                    }
-                }
-            }
-            finally
+            var request = (HttpWebRequest)WebRequest.Create(url);
+            request.Timeout = 20000;
+            request.AllowAutoRedirect = false;
+            using (var response = (HttpWebResponse)request.GetResponse())
             {
-                if (response != null)
+                if (response.StatusCode != HttpStatusCode.OK || response.ContentLength >= 1024 * 1024)
                 {
-                    response.Close();
-                    response = null;
+                    return Encoding.Default.BodyName;
                 }
-                if (reader != null)
-                    reader.Close();
-                if (request != null)
-                    request = null;
-            }
-            return Encoding.Default.BodyName;
-        }
-        #endregion
 
-        #region 判断URL是否有效
+                var reader = response.ContentEncoding.Equals("gzip") ? new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) : new StreamReader(response.GetResponseStream(), Encoding.ASCII);
 
-        /// <summary>
-        /// 判断URL是否有效
-        /// </summary>
-        /// <param name="_"></param>
-        /// <param name="url">待判断的URL,可以是网页以及图片链接等</param>
-        /// <returns>200为正确,其余为大致网页错误代码</returns>
-        public static int GetUrlError(this HttpWebRequest _, string url)
-        {
-            int num = 200;
-            try
-            {
-                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
-                ServicePointManager.Expect100Continue = false;
-                ((HttpWebResponse)request.GetResponse()).Close();
-            }
-            catch (WebException exception)
-            {
-                if (exception.Status != WebExceptionStatus.ProtocolError)
-                {
-                    return num;
-                }
-                if (exception.Message.IndexOf("500 ") > 0)
-                {
-                    return 500;
-                }
-                if (exception.Message.IndexOf("401 ") > 0)
+                string html = reader.ReadToEnd();
+                Regex regCharset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
+                if (regCharset.IsMatch(html))
                 {
-                    return 401;
+                    return regCharset.Match(html).Groups["charset"].Value;
                 }
-                if (exception.Message.IndexOf("404") > 0)
+
+                if (response.CharacterSet != string.Empty)
                 {
-                    num = 404;
+                    return response.CharacterSet;
                 }
             }
-            catch
-            {
-                num = 401;
-            }
-            return num;
+
+            return Encoding.Default.BodyName;
         }
+
         #endregion
 
         #region 返回 HTML 字符串的编码解码结果
+
         /// <summary>
         /// 返回 HTML 字符串的编码结果
         /// </summary>
@@ -829,6 +640,7 @@ namespace Masuit.Tools.Html
         {
             return HttpUtility.HtmlDecode(str);
         }
+
         #endregion
 
         /// <summary>
@@ -839,7 +651,6 @@ namespace Masuit.Tools.Html
         /// <returns>Cookie键值集合</returns>
         public static CookieCollection GetCookieCollection(this CookieCollection cookie, string cookieString)
         {
-            //string cookieString = "SID=ARRGy4M1QVBtTU-ymi8bL6X8mVkctYbSbyDgdH8inu48rh_7FFxHE6MKYwqBFAJqlplUxq7hnBK5eqoh3E54jqk=;Domain=.google.com;Path=/,LSID=AaMBTixN1MqutGovVSOejyb8mVkctYbSbyDgdH8inu48rh_7FFxHE6MKYwqBFAJqlhCe_QqxLg00W5OZejb_UeQ=;Domain=www.google.com;Path=/accounts";
             Regex re = new Regex("([^;,]+)=([^;,]+);Domain=([^;,]+);Path=([^;,]+)", RegexOptions.IgnoreCase);
             foreach (Match m in re.Matches(cookieString))
             {
@@ -847,6 +658,7 @@ namespace Masuit.Tools.Html
                 Cookie c = new Cookie(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value, m.Groups[3].Value);
                 cookie.Add(c);
             }
+
             return cookie;
         }
 
@@ -863,6 +675,7 @@ namespace Masuit.Tools.Html
 
             return regEx.Replace(HTML, "");
         }
+
         #endregion
 
         #region 获取HTML页面内制定Key的Value内容
@@ -883,8 +696,10 @@ namespace Masuit.Tools.Html
             {
                 result = mc.Groups[1].Value;
             }
+
             return result;
         }
+
         #endregion
 
         /// <summary>
@@ -893,19 +708,13 @@ namespace Masuit.Tools.Html
         /// <param name="str">html</param>
         public static string StrFormat(this string str)
         {
-            string str2;
-            if (str == null)
-            {
-                str2 = "";
-            }
-            else
-            {
-                str = str.Replace("\r\n", "<br />");
-                str = str.Replace("\n", "<br />");
-                str2 = str;
-            }
+            str = str.Replace("\r\n", "<br />");
+            str = str.Replace("\n", "<br />");
+            var str2 = str;
+
             return str2;
         }
+
         /// <summary>
         /// 替换html字符
         /// </summary>
@@ -919,6 +728,7 @@ namespace Masuit.Tools.Html
                 strHtml = strHtml.Replace(";", "&dec");
                 return strHtml;
             }
+
             return "";
         }
 

文件差異過大導致無法顯示
+ 184 - 229
Masuit.Tools/Html/HtmlTools.cs


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

@@ -21,6 +21,7 @@ namespace Masuit.Tools.Logging
         /// 自定义事件
         /// </summary>
         public static event Action<LogInfo> Event;
+
         static LogManager()
         {
             var writeTask = new Task(obj =>
@@ -40,11 +41,17 @@ namespace Masuit.Tools.Logging
                         }
                         else
                         {
-                            logArr = new[] { logPath, logMergeContent };
+                            logArr = new[]
+                            {
+                                logPath,
+                                logMergeContent
+                            };
                             temp.Add(logArr);
                         }
+
                         LogQueue.TryDequeue(out Tuple<string, string> _);
                     }
+
                     foreach (var item in temp)
                     {
                         WriteText(item[0], item[1]);
@@ -62,8 +69,11 @@ namespace Masuit.Tools.Logging
         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 { }
+            set
+            {
+            }
         }
+
         /// <summary>
         /// 写入Info级别的日志
         /// </summary>
@@ -389,6 +399,7 @@ namespace Masuit.Tools.Logging
             {
                 Directory.CreateDirectory(logDir);
             }
+
             string extension = ".log";
             string fileNameNotExt = Now.ToString("yyyyMMdd");
             string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension);
@@ -416,6 +427,7 @@ namespace Masuit.Tools.Logging
                 string newFileName = string.Concat(fileNameNotExt, $"({0})", extension);
                 newFilePath = Path.Combine(logDir, newFileName);
             }
+
             return newFilePath;
         }
 
@@ -427,6 +439,7 @@ namespace Masuit.Tools.Logging
                 {
                     File.CreateText(logPath).Close();
                 }
+
                 using (StreamWriter sw = File.AppendText(logPath))
                 {
                     sw.Write(logContent);

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

@@ -70,11 +70,12 @@
   <ItemGroup>
     <Compile Include="Database\DataTableHelper.cs" />
     <Compile Include="DateTimeExt\ChineseCalendar.cs" />
-    <Compile Include="DateTimeExt\CNCalendar.cs" />
     <Compile Include="Database\DataExt.cs" />
     <Compile Include="DateTimeExt\DateTimeHelper.cs" />
     <Compile Include="DateTimeExt\DateUtil.cs" />
+    <Compile Include="DateTimeExt\DateInfoStruct.cs" />
     <Compile Include="DateTimeExt\TimeHelper.cs" />
+    <Compile Include="DateTimeExt\WeekHolidayStruct.cs" />
     <Compile Include="ExpressionGenericMapper.cs" />
     <Compile Include="Extensions.cs" />
     <Compile Include="Files\Compress.cs" />

+ 10 - 13
Masuit.Tools/Media/ImageUtilities.cs

@@ -242,7 +242,7 @@ namespace Masuit.Tools.Media
                     ImageCodecInfo ici = null;
                     foreach (ImageCodecInfo i in icis)
                     {
-                        if ((i.MimeType == "image/jpeg") || (i.MimeType == "image/bmp") || (i.MimeType == "image/png") || (i.MimeType == "image/gif"))
+                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                             ici = i;
                     }
 
@@ -481,12 +481,13 @@ namespace Masuit.Tools.Media
         /// <returns>剪裁后的Bitmap</returns>
         public static Bitmap CutImage(this Bitmap b, Rectangle rec)
         {
-            if (b == null)
-                return null;
             int w = b.Width;
             int h = b.Height;
             if ((rec.X >= w) || (rec.Y >= h))
+            {
                 return null;
+            }
+
             if (rec.X + rec.Width > w)
                 rec.Width = w - rec.X;
             if (rec.Y + rec.Height > h)
@@ -839,12 +840,11 @@ namespace Masuit.Tools.Media
         {
             Bitmap bm = new Bitmap(width, height); //初始化一个记录经过处理后的图片对象
             int x, y; //x、y是循环次数,后面三个是记录红绿蓝三个值的
-            Color pixel;
             for (x = 0; x < width; x++)
             {
                 for (y = 0; y < height; y++)
                 {
-                    pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                    var pixel = mybm.GetPixel(x, y);
                     var resultR = pixel.R + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
                     var resultG = pixel.G + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
                     var resultB = pixel.B + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
@@ -997,12 +997,11 @@ namespace Masuit.Tools.Media
             using (Bitmap bm = new Bitmap(width, height))
             {
                 int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
-                Color pixel;
                 for (y = height - 1; y >= 0; y--)
                 {
                     for (x = width - 1, z = 0; x >= 0; x--)
                     {
-                        pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                        var pixel = mybm.GetPixel(x, y);
                         bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                     }
                 }
@@ -1027,12 +1026,11 @@ namespace Masuit.Tools.Media
             using (bm)
             {
                 int x, y, z;
-                Color pixel;
                 for (x = 0; x < width; x++)
                 {
                     for (y = height - 1, z = 0; y >= 0; y--)
                     {
-                        pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                        var pixel = mybm.GetPixel(x, y);
                         bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
                     }
                 }
@@ -1117,14 +1115,13 @@ namespace Masuit.Tools.Media
             Bitmap bm = new Bitmap(width, height);
             using (bm)
             {
-                int x, y, result; //x,y是循环次数,result是记录处理后的像素值
-                Color pixel;
+                int x, y; //x,y是循环次数
                 for (x = 0; x < width; x++)
                 {
                     for (y = 0; y < height; y++)
                     {
-                        pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
-                        result = (pixel.R + pixel.G + pixel.B) / 3; //取红绿蓝三色的平均
+                        var pixel = mybm.GetPixel(x, y);
+                        var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素
                         bm.SetPixel(x, y, Color.FromArgb(result, result, result));
                     }
                 }

+ 24 - 21
Masuit.Tools/Net/CacheHelper.cs

@@ -1,7 +1,6 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
-using System.Web;
 using System.Web.Caching;
 
 namespace Masuit.Tools.Net
@@ -18,11 +17,12 @@ namespace Masuit.Tools.Net
         /// </summary>
         /// <typeparam name="T">返回的类型</typeparam>
         /// <param name="cache"></param>
-        /// <param name="CacheKey">键</param>
-        public static T GetCache<T>(this Cache cache, string CacheKey)
+        /// <param name="cacheKey">键</param>
+        public static T GetCache<T>(this Cache cache, string cacheKey)
         {
-            return (T)cache[CacheKey];
+            return (T)cache[cacheKey];
         }
+
         #endregion
 
         #region  设置数据缓存
@@ -31,11 +31,11 @@ namespace Masuit.Tools.Net
         /// 设置数据缓存
         /// </summary>
         /// <param name="cache"></param>
-        /// <param name="CacheKey">键</param>
+        /// <param name="cacheKey">键</param>
         /// <param name="objObject">值</param>
-        public static void SetCache(this Cache cache, string CacheKey, object objObject)
+        public static void SetCache(this Cache cache, string cacheKey, object objObject)
         {
-            cache.Insert(CacheKey, objObject);
+            cache.Insert(cacheKey, objObject);
         }
 
         /// <summary>
@@ -44,26 +44,27 @@ namespace Masuit.Tools.Net
         /// <param name="cache"></param>
         /// <param name="cacheKey">键</param>
         /// <param name="objObject">值</param>
-        /// <param name="Timeout">过期时间</param>
+        /// <param name="timeout">过期时间</param>
         /// <exception cref="ArgumentNullException"><paramref name="cacheKey"/>"/> is <c>null</c>.</exception>
-        public static void SetCache(this Cache cache, string cacheKey, object objObject, TimeSpan Timeout)
+        public static void SetCache(this Cache cache, string cacheKey, object objObject, TimeSpan timeout)
         {
             if (cacheKey == null) throw new ArgumentNullException(nameof(cacheKey));
-            cache.Insert(cacheKey, objObject, null, DateTime.MaxValue, Timeout, CacheItemPriority.NotRemovable, null);
+            cache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
         }
 
         /// <summary>
         /// 设置当前应用程序指定CacheKey的Cache值
         /// </summary>
         /// <param name="cache"></param>
-        /// <param name="CacheKey">键</param>
+        /// <param name="cacheKey">键</param>
         /// <param name="objObject">值</param>
         /// <param name="absoluteExpiration">绝对过期时间</param>
         /// <param name="slidingExpiration">滑动过期时间</param>
-        public static void SetCache(this Cache cache, string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
+        public static void SetCache(this Cache cache, string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
         {
-            cache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
+            cache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration);
         }
+
         #endregion
 
         #region   移除缓存
@@ -72,25 +73,26 @@ namespace Masuit.Tools.Net
         /// 移除指定数据缓存
         /// </summary>
         /// <param name="cache"></param>
-        /// <param name="CacheKey">键</param>
-        public static void RemoveAllCache(this Cache cache, string CacheKey) => cache.Remove(CacheKey);
+        /// <param name="cacheKey">键</param>
+        public static void RemoveAllCache(this Cache cache, string cacheKey) => cache.Remove(cacheKey);
 
         /// <summary>
         /// 移除全部缓存
         /// </summary>
         public static void RemoveAllCache(this Cache cache)
         {
-            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
-            while (CacheEnum.MoveNext())
+            IDictionaryEnumerator cacheEnum = cache.GetEnumerator();
+            while (cacheEnum.MoveNext())
             {
-                cache.Remove(CacheEnum.Key.ToString());
+                cache.Remove(cacheEnum.Key.ToString());
             }
         }
+
         #endregion
 
         private static SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
-        private static volatile Cache instance = null;
-        private static object lockHelper = new object();
+        private static volatile Cache instance;
+        private static readonly object LockHelper = new object();
 
         /// <summary>
         /// 添加缓存数据
@@ -111,7 +113,7 @@ namespace Masuit.Tools.Net
             {
                 if (instance == null)
                 {
-                    lock (lockHelper)
+                    lock (LockHelper)
                     {
                         if (instance == null)
                         {
@@ -119,6 +121,7 @@ namespace Masuit.Tools.Net
                         }
                     }
                 }
+
                 return instance;
             }
         }

+ 70 - 29
Masuit.Tools/Net/CookieHelper.cs

@@ -1,4 +1,5 @@
-using System;
+using Masuit.Tools.Logging;
+using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Net;
@@ -7,7 +8,6 @@ using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 using System.Web;
-using Masuit.Tools.Logging;
 
 namespace Masuit.Tools.Net
 {
@@ -37,11 +37,15 @@ namespace Masuit.Tools.Net
                 cookieData = new StringBuilder(datasize);
                 if (!InternetGetCookie(uri.ToString(), null, cookieData, ref datasize)) return null;
             }
-            if (cookieData.Length > 0)
+
+            if (cookieData.Length <= 0)
             {
-                cookies = new CookieContainer();
-                cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
+                return cookies;
             }
+
+            cookies = new CookieContainer();
+            cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
+
             return cookies;
         }
 
@@ -59,12 +63,14 @@ namespace Masuit.Tools.Net
             {
                 sb.AppendLine(string.Format("{0}:{1}", cook.Name, cook.Value));
             }
+
             return sb.ToString();
         }
 
         #region 清除CooKie 
 
         #region 清除指定Cookie
+
         /// <summary>
         /// 清除指定Cookie
         /// </summary>
@@ -78,9 +84,11 @@ namespace Masuit.Tools.Net
                 HttpContext.Current.Response.Cookies.Add(cookie);
             }
         }
+
         #endregion
 
         #region   删除所有cookie值
+
         /// <summary>
         /// 删除所有cookie值
         /// </summary>
@@ -89,14 +97,16 @@ namespace Masuit.Tools.Net
             int n = HttpContext.Current.Response.Cookies.Count;
             for (int i = 0; i < n; i++)
             {
-                HttpCookie MyCookie = HttpContext.Current.Response.Cookies[i];
-                MyCookie.Expires = DateTime.Now.AddDays(-1);
-                HttpContext.Current.Response.Cookies.Add(MyCookie);
+                HttpCookie myCookie = HttpContext.Current.Response.Cookies[i];
+                myCookie.Expires = DateTime.Now.AddDays(-1);
+                HttpContext.Current.Response.Cookies.Add(myCookie);
             }
         }
+
         #endregion
 
         #region 清除系统指定的Cookie
+
         /// <summary>
         /// 清除系统指定的Cookie
         /// </summary>
@@ -115,6 +125,7 @@ namespace Masuit.Tools.Net
                 }
             }
         }
+
         #endregion
 
         #region 清除系统的Cookie文件
@@ -137,7 +148,9 @@ namespace Masuit.Tools.Net
                 }
             }
         }
+
         #endregion
+
         #endregion
 
         #region 获取Cookie
@@ -157,22 +170,24 @@ namespace Masuit.Tools.Net
             {
                 str = cookie.Value;
             }
+
             return str;
         }
 
         /// <summary>
         /// 根据Key值得到Cookie值,Key不区分大小写
         /// </summary>
-        /// <param name="Key">key</param>
+        /// <param name="key">key</param>
         /// <param name="cookie">字符串Cookie</param>
         /// <returns>Cookie值</returns>
-        public static string GetCookieValue(string Key, string cookie)
+        public static string GetCookieValue(string key, string cookie)
         {
             foreach (CookieItem item in GetCookieList(cookie))
             {
-                if (item.Key == Key)
+                if (item.Key == key)
                     return item.Value;
             }
+
             return "";
         }
 
@@ -184,16 +199,26 @@ namespace Masuit.Tools.Net
         public static List<CookieItem> GetCookieList(string cookie)
         {
             List<CookieItem> cookielist = new List<CookieItem>();
-            foreach (string item in cookie.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries))
+            foreach (string item in cookie.Split(new[]
+            {
+                ";",
+                ","
+            }, StringSplitOptions.RemoveEmptyEntries))
             {
                 if (Regex.IsMatch(item, @"([\s\S]*?)=([\s\S]*?)$"))
                 {
                     Match m = Regex.Match(item, @"([\s\S]*?)=([\s\S]*?)$");
-                    cookielist.Add(new CookieItem() { Key = m.Groups[1].Value, Value = m.Groups[2].Value });
+                    cookielist.Add(new CookieItem()
+                    {
+                        Key = m.Groups[1].Value,
+                        Value = m.Groups[2].Value
+                    });
                 }
             }
+
             return cookielist;
         }
+
         #endregion
 
         #region  获取cookie数组
@@ -205,15 +230,9 @@ namespace Masuit.Tools.Net
         /// <returns>字符串数组</returns>
         public static string[] GetCKS(string ck)
         {
-            if (ck != null)
-            {
-                return ck.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
-            }
-            else
-            {
-                return new string[0];
-            }
+            return ck == null ? new string[0] : ck.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
         }
+
         #endregion
 
         #region  从Cookie数组中转换成不重复的Cookie字符串,相同的Cookie取前面的
@@ -237,12 +256,15 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
-            for (int i = 0; i < list.Count; i++)
+
+            foreach (var t in list)
             {
-                res += list[i] + ";";
+                res += t + ";";
             }
+
             return res;
         }
+
         #endregion
 
         #region  从CookieCollection中获取Cookie字符串
@@ -259,8 +281,10 @@ namespace Masuit.Tools.Net
             {
                 ck += cc[i].Name + "=" + cc[i].Value + ";";
             }
+
             return ck;
         }
+
         #endregion
 
         #region   将Cookie字符串填充到CookieCollection中
@@ -299,9 +323,12 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
+
             return cc;
         }
+
         #endregion
+
         #endregion
 
         #region 添加Cookie
@@ -317,9 +344,11 @@ namespace Masuit.Tools.Net
         {
             SetCookie(cookiename, cookievalue, DateTime.Now.AddDays(1.0));
         }
+
         #endregion
 
         #region   添加一个Cookie
+
         /// <summary>
         /// 添加一个Cookie
         /// </summary>
@@ -335,7 +364,9 @@ namespace Masuit.Tools.Net
             };
             HttpContext.Current.Response.Cookies.Add(cookie);
         }
+
         #endregion
+
         #endregion
 
         #region 检查Cookie集合中是否包含指定的Cookie值
@@ -357,9 +388,11 @@ namespace Masuit.Tools.Net
                         return true;
                     }
                 }
+
                 return false;
             }).ConfigureAwait(false);
         }
+
         #endregion
 
         #region 设置系统Cookie
@@ -371,8 +404,9 @@ namespace Masuit.Tools.Net
         /// <param name="lbszCookieName">Cookie名</param>
         /// <param name="lpszCookieData">Cookie数据</param>
         /// <returns>设置成功与否</returns>
-        [System.Runtime.InteropServices.DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
+        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
         public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
+
         #endregion
 
         #region   获取所有可能的Cookie域
@@ -393,8 +427,10 @@ namespace Masuit.Tools.Net
                 baseDomain += t;
                 res.Add(baseDomain);
             }
+
             return res;
         }
+
         #endregion
 
         #region  将Cookie字符串描述的Cookie追加到CookieCoollection
@@ -413,6 +449,7 @@ namespace Masuit.Tools.Net
                 cc.Add(tmp[i]);
             }
         }
+
         #endregion
 
         #region 将Cookie字符串设置到系统中,便于浏览器使用
@@ -425,15 +462,17 @@ namespace Masuit.Tools.Net
         public static void SetCKToSystem(string ck, string url)
         {
             string[] cks = GetCKS(ck);
-            for (int i = 0; i < cks.Length; i++)
+            foreach (var t in cks)
             {
-                string[] nv = cks[i].Split('=');
+                string[] nv = t.Split('=');
                 InternetSetCookie(url, nv[0], nv.Length > 1 ? nv[1] : "");
             }
         }
+
         #endregion
 
         #region 将CookieCollection中的Cookie设置到系统中,便于浏览器使用
+
         /// <summary>
         /// 将CookieCollection中的Cookie设置到系统中,便于浏览器使用
         /// </summary>
@@ -444,12 +483,13 @@ namespace Masuit.Tools.Net
             List<string> domains = GetDomains(url);
             for (int i = 0; i < cc.Count; i++)
             {
-                for (int j = 0; j < domains.Count; j++)
+                foreach (var t in domains)
                 {
-                    InternetSetCookie(domains[j], cc[i].Name, cc[i].Value);
+                    InternetSetCookie(t, cc[i].Name, cc[i].Value);
                 }
             }
         }
+
         #endregion
 
         /// <summary>
@@ -473,9 +513,10 @@ namespace Masuit.Tools.Net
         /// 键
         /// </summary>
         public string Key { get; set; }
+
         /// <summary>
         /// 值
         /// </summary>
         public string Value { get; set; }
     }
-}
+}

+ 27 - 1
Masuit.Tools/Net/FtpClient.cs

@@ -50,6 +50,7 @@ namespace Masuit.Tools.Net
                 {
                     throw new Exception("ftp下载目标服务器地址未设置!");
                 }
+
                 Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
                 var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
                 ftpsize.UseBinary = true;
@@ -61,6 +62,7 @@ namespace Masuit.Tools.Net
                     ftpsize.Credentials = new NetworkCredential(Username, Password);
                     reqFtp.Credentials = new NetworkCredential(Username, Password);
                 }
+
                 ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                 using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
                 {
@@ -111,6 +113,7 @@ namespace Masuit.Tools.Net
                 {
                     throw new Exception("ftp下载目标服务器地址未设置!");
                 }
+
                 Uri uri = new Uri("ftp://" + FtpServer + "/" + remoteFileName);
                 var ftpsize = (FtpWebRequest)WebRequest.Create(uri);
                 ftpsize.UseBinary = true;
@@ -124,6 +127,7 @@ namespace Masuit.Tools.Net
                     ftpsize.Credentials = new NetworkCredential(Username, Password);
                     reqFtp.Credentials = new NetworkCredential(Username, Password);
                 }
+
                 ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                 using (FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse())
                 {
@@ -175,8 +179,10 @@ namespace Masuit.Tools.Net
                         size = outputStream.Length;
                     }
                 }
+
                 BrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress);
             }
+
             Download(remoteFileName, localFileName, ifCredential, updateProgress);
         }
 
@@ -196,6 +202,7 @@ namespace Masuit.Tools.Net
             {
                 throw new Exception("ftp上传目标服务器地址未设置!");
             }
+
             Uri uri = new Uri("ftp://" + FtpServer + "/" + finfo.Name);
             var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
             reqFtp.KeepAlive = false;
@@ -239,6 +246,7 @@ namespace Masuit.Tools.Net
             {
                 remoteFilepath = "";
             }
+
             string newFileName;
             FileInfo fileInf = new FileInfo(localFullPath);
             long allbye = fileInf.Length;
@@ -251,11 +259,13 @@ namespace Masuit.Tools.Net
                 newFileName = fileInf.Name.Replace("#", "#");
                 newFileName = RemoveSpaces(newFileName);
             }
+
             long startfilesize = GetFileSize(newFileName, remoteFilepath);
             if (startfilesize >= allbye)
             {
                 return false;
             }
+
             long startbye = startfilesize;
             //更新进度 
             updateProgress?.Invoke((int)allbye, (int)startfilesize); //更新进度条 
@@ -269,6 +279,7 @@ namespace Masuit.Tools.Net
             {
                 uri = "ftp://" + FtpServer + "/" + remoteFilepath + "/" + newFileName;
             }
+
             // 根据uri创建FtpWebRequest对象 
             var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri));
             // ftp用户名和密码 
@@ -304,6 +315,7 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
+
             return true;
         }
 
@@ -324,6 +336,7 @@ namespace Masuit.Tools.Net
                     a += c.ToString();
                 }
             }
+
             return a.Split('.')[a.Split('.').Length - 2] + "." + a.Split('.')[a.Split('.').Length - 1];
         }
 
@@ -347,6 +360,7 @@ namespace Masuit.Tools.Net
                 {
                     uri = "ftp://" + FtpServer + "/" + remoteFilepath + "/" + fi.Name;
                 }
+
                 var reqFtp = (FtpWebRequest)WebRequest.Create(uri);
                 reqFtp.KeepAlive = false;
                 reqFtp.UseBinary = true;
@@ -387,9 +401,11 @@ namespace Masuit.Tools.Net
                         result.Append("\n");
                         line = reader.ReadLine();
                     }
+
                     result.Remove(result.ToString().LastIndexOf("\n", StringComparison.Ordinal), 1);
                 }
             }
+
             return result.ToString().Split('\n');
         }
 
@@ -425,11 +441,14 @@ namespace Masuit.Tools.Net
                             result.Append(line);
                             result.Append("\n");
                         }
+
                         line = reader.ReadLine();
                     }
+
                     result.Remove(result.ToString().LastIndexOf('\n'), 1);
                 }
             }
+
             return result.ToString().Split('\n');
         }
 
@@ -459,7 +478,11 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
-            char[] n = { '\n' };
+
+            char[] n =
+            {
+                '\n'
+            };
             return m.Split(n);
         }
 
@@ -553,6 +576,7 @@ namespace Masuit.Tools.Net
                         return true;
                     }
                 }
+
                 return false;
             }
             catch
@@ -575,6 +599,7 @@ namespace Masuit.Tools.Net
                     return true;
                 }
             }
+
             return false;
         }
 
@@ -642,6 +667,7 @@ namespace Masuit.Tools.Net
             {
                 _ftpRemotePath += directoryName + "/";
             }
+
             FtpUri = "ftp://" + FtpServer + "/" + _ftpRemotePath + "/";
         }
 

+ 42 - 14
Masuit.Tools/Net/MultiThreadDownloader.cs

@@ -21,19 +21,24 @@ namespace Masuit.Tools.Net
     /// </summary>
     public class MultiThreadDownloader
     {
-        #region Variables
+        #region 变量
+
         /// <summary>
         /// 总下载进度更新事件
         /// </summary>
         public event EventHandler TotalProgressChanged;
+
         /// <summary>
         /// 文件合并事件
         /// </summary>
         public event FileMergeProgressChangedEventHandler FileMergeProgressChanged;
+
         private readonly AsyncOperation _aop;
+
         #endregion
 
-        #region DownloadManager
+        #region 下载管理器
+
         public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts)
         {
             _url = sourceUrl;
@@ -43,16 +48,19 @@ namespace Masuit.Tools.Net
             _aop = AsyncOperationManager.CreateOperation(null);
             FilePath = savePath;
         }
+
         public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, savePath, numOfParts)
         {
             TempFileDirectory = Environment.GetEnvironmentVariable("temp");
         }
+
         public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts)
         {
         }
+
         #endregion
 
-        #region Events
+        #region 事件
 
         private void temp_DownloadPartCompleted(object sender, EventArgs e)
         {
@@ -81,6 +89,7 @@ namespace Masuit.Tools.Net
                 WaitOrResumeAll(PartialDownloaderList, false);
                 return;
             }
+
             PartialDownloaderList[0].To = from - 1;
 
             WaitOrResumeAll(PartialDownloaderList, false);
@@ -109,9 +118,11 @@ namespace Masuit.Tools.Net
                 }
             }
         }
+
         #endregion
 
-        #region Helpers
+        #region 方法
+
         void CreateFirstPartitions()
         {
             Size = GetContentLength(_url, ref _rangeAllowed, ref _url);
@@ -131,6 +142,7 @@ namespace Masuit.Tools.Net
                 temp.Start();
             }
         }
+
         void MergeParts()
         {
             List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
@@ -156,10 +168,12 @@ namespace Masuit.Tools.Net
                             }
                         }
                     }
+
                     File.Delete(item.FullPath);
                 }
             }
         }
+
         PartialDownloader CreateNewPd(int order, int parts, long contentLength)
         {
             int division = (int)contentLength / parts;
@@ -169,6 +183,7 @@ namespace Masuit.Tools.Net
             end += (order == parts - 1) ? remaining : 0;
             return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), start, end, true);
         }
+
         public static void WaitOrResumeAll(List<PartialDownloader> list, bool wait)
         {
             foreach (PartialDownloader item in list)
@@ -199,11 +214,13 @@ namespace Masuit.Tools.Net
                 }
             }
         }
+
         //Sorts the downloader by From property to merge the parts
         public static List<PartialDownloader> SortPDsByFrom(List<PartialDownloader> list)
         {
             return list.OrderBy(x => x.From).ToList();
         }
+
         public static void OrderByRemaining(List<PartialDownloader> list)
         {
             BubbleSort(list);
@@ -214,17 +231,26 @@ namespace Masuit.Tools.Net
             HttpWebRequest 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;
-            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
-            redirectedUrl = resp.ResponseUri.OriginalString;
-            long 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();
+            long ctl;
+            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
+            {
+                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();
+            }
+
             req.Abort();
             return ctl;
         }
+
         #endregion
 
-        #region Public Methods
+        #region 公共方法
 
         /// <summary>
         /// 暂停下载
@@ -273,21 +299,24 @@ namespace Masuit.Tools.Net
                 }
             }
         }
+
         #endregion
 
-        #region Property Variables
+        #region 属性
 
         private string _url;
         private bool _rangeAllowed;
 
         #endregion
 
-        #region Properties
+        #region 公共属性
+
         public bool RangeAllowed
         {
             get => _rangeAllowed;
             set => _rangeAllowed = value;
         }
+
         public string TempFileDirectory { get; set; }
 
         public string Url
@@ -310,6 +339,5 @@ namespace Masuit.Tools.Net
         public string FilePath { get; set; }
 
         #endregion
-
     }
-}
+}

+ 25 - 6
Masuit.Tools/Net/PartialDownloader.cs

@@ -11,6 +11,7 @@ namespace Masuit.Tools.Net
     public class PartialDownloader
     {
         #region Variables
+
         public event EventHandler DownloadPartCompleted;
         public event EventHandler DownloadPartProgressChanged;
         public event EventHandler DownloadPartStopped;
@@ -23,9 +24,11 @@ namespace Masuit.Tools.Net
         readonly int[] _lastSpeeds;
         int _counter;
         bool _stop, _wait;
+
         #endregion
 
         #region PartialDownloader
+
         public PartialDownloader(string url, string dir, string fileGuid, int from, int to, bool rangeAllowed)
         {
             _from = from;
@@ -37,12 +40,15 @@ namespace Masuit.Tools.Net
             _lastSpeeds = new int[10];
             _stp = new Stopwatch();
         }
+
         #endregion
 
         void DownloadProcedure()
         {
             _file = new FileStream(FullPath, FileMode.Create, FileAccess.ReadWrite);
+
             #region Request-Response
+
             _req = WebRequest.Create(_url) as HttpWebRequest;
             if (_req != null)
             {
@@ -83,16 +89,19 @@ namespace Masuit.Tools.Net
                         }
 
                         if (_totalBytesRead + bytesRead > _contentLength)
-                            bytesRead = (int)(_contentLength - _totalBytesRead);
+                            bytesRead = (int) (_contentLength - _totalBytesRead);
                         _file.Write(buffer, 0, bytesRead);
                         _totalBytesRead += bytesRead;
-                        _lastSpeeds[_counter] = (int)(_totalBytesRead / Math.Ceiling(_stp.Elapsed.TotalSeconds));
+                        _lastSpeeds[_counter] = (int) (_totalBytesRead / Math.Ceiling(_stp.Elapsed.TotalSeconds));
                         _counter = (_counter >= 9) ? 0 : _counter + 1;
-                        int tempProgress = (int)(_totalBytesRead * 100 / _contentLength);
+                        int tempProgress = (int) (_totalBytesRead * 100 / _contentLength);
                         if (_progress != tempProgress)
                         {
                             _progress = tempProgress;
-                            _aop.Post(state => { DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty); }, null);
+                            _aop.Post(state =>
+                            {
+                                DownloadPartProgressChanged?.Invoke(this, EventArgs.Empty);
+                            }, null);
                         }
 
                         if (_stop || (_rangeAllowed && _totalBytesRead == _contentLength))
@@ -114,9 +123,11 @@ namespace Masuit.Tools.Net
             }
 
             _stp.Stop();
+
             #endregion
 
             #region Fire Events
+
             if (!_stop && DownloadPartCompleted != null)
                 _aop.Post(state =>
                 {
@@ -131,6 +142,7 @@ namespace Masuit.Tools.Net
         }
 
         #region Public Methods
+
         public void Start()
         {
             _stop = false;
@@ -142,18 +154,22 @@ namespace Masuit.Tools.Net
         {
             _stop = true;
         }
+
         //Wait is used when repartitiate a partition securely in this project
         public void Wait()
         {
             _wait = true;
         }
+
         public void ResumeAfterWait()
         {
             _wait = false;
         }
+
         #endregion
 
         #region Property Variables
+
         private readonly int _from;
         private int _to;
         private readonly string _url;
@@ -164,9 +180,11 @@ namespace Masuit.Tools.Net
         private readonly string _directory;
         private int _progress;
         private bool _completed;
+
         #endregion
 
         #region Properties
+
         public bool Stopped => _stop;
 
         public bool Completed => _completed;
@@ -199,7 +217,7 @@ namespace Masuit.Tools.Net
 
         public int CurrentPosition => _from + _totalBytesRead - 1;
 
-        public int RemainingBytes => (int)(_contentLength - _totalBytesRead);
+        public int RemainingBytes => (int) (_contentLength - _totalBytesRead);
 
         public string FullPath => Path.Combine(_directory, _fileGuid);
 
@@ -215,6 +233,7 @@ namespace Masuit.Tools.Net
                 return totalSpeeds / 10;
             }
         }
+
         #endregion
     }
-}
+}

+ 14 - 6
Masuit.Tools/Net/SocketClient.cs

@@ -155,17 +155,17 @@ namespace Masuit.Tools.Net
         public static byte[] ReceiveFixData(this Socket socket, int size)
         {
             int offset = 0;
-            int recv = 0;
             int dataleft = size;
             byte[] msg = new byte[size];
             while (dataleft > 0)
             {
-                recv = socket.Receive(msg, offset, dataleft, 0);
+                var recv = socket.Receive(msg, offset, dataleft, 0);
                 if (recv == 0)
                     break;
                 offset += recv;
                 dataleft -= recv;
             }
+
             return msg;
         }
 
@@ -226,11 +226,13 @@ namespace Masuit.Tools.Net
                     if (mark == 10)
                         break;
                 }
+
                 if (offset == length)
                     break;
             }
+
             stream.Seek(0, SeekOrigin.Begin); //必须要这个 或者stream.Position = 0;
-            T t = (T)format.Deserialize(stream);
+            T t = (T) format.Deserialize(stream);
             stream.Close();
             return t;
         }
@@ -253,7 +255,6 @@ namespace Masuit.Tools.Net
                 string savepath = GetPath(path, filename); //得到文件路径
                 //缓冲区
                 byte[] file = new byte[m_maxpacket];
-                int count = 0; //每次接收的实际长度
                 int receivedata = m_maxpacket; //每次要接收的长度
                 long offset = 0; //循环接收的总长度
                 long lastdata = size; //剩余多少还没接收
@@ -265,7 +266,7 @@ namespace Masuit.Tools.Net
                         {
                             if (lastdata < receivedata)
                                 receivedata = Convert.ToInt32(lastdata);
-                            count = socket.Receive(file, 0, receivedata, SocketFlags.None);
+                            var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
                             if (count > 0)
                             {
                                 fs.Write(file, 0, count);
@@ -279,6 +280,7 @@ namespace Masuit.Tools.Net
                                 if (mark == 10)
                                     break;
                             }
+
                             //接收进度
                             if (progress != null)
                                 progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
@@ -289,9 +291,11 @@ namespace Masuit.Tools.Net
                                 break;
                             }
                         }
+
                     fs.Close();
                 }
             }
+
             return ret;
         }
 
@@ -346,6 +350,7 @@ namespace Masuit.Tools.Net
         private static int i;
 
         private static string markPath = string.Empty;
+
         /// <summary>
         /// 得到文件路径(防止有文件名重复)
         ///  如:aaa.txt已经在directory目录下存在,则会得到文件aaa(1).txt
@@ -353,7 +358,6 @@ namespace Masuit.Tools.Net
         /// <param name="directory">目录名</param>
         /// <param name="file">文件名</param>
         /// <returns>文件路径</returns>
-
         public static string GetPath(string directory, string file)
         {
             if (markPath == string.Empty)
@@ -366,6 +370,7 @@ namespace Masuit.Tools.Net
                 string extension = Path.GetExtension(markPath);
                 return GetPath(directory, filename + extension);
             }
+
             i = 0;
             markPath = string.Empty;
             return path;
@@ -399,6 +404,7 @@ namespace Masuit.Tools.Net
                 if (offset == size)
                     break;
             }
+
             return offset;
         }
 
@@ -494,6 +500,7 @@ namespace Masuit.Tools.Net
                             if (mark == 10)
                                 break;
                         }
+
                         if (progress != null)
                             progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
                         if (offset == length)
@@ -502,6 +509,7 @@ namespace Masuit.Tools.Net
                     }
                 }
             }
+
             return ret;
         }
 

+ 41 - 6
Masuit.Tools/Net/WebExtension.cs

@@ -35,7 +35,8 @@ namespace Masuit.Tools.Net
                 db = new T();
                 CallContext.SetData("db", db);
             }
-            db = (T)CallContext.GetData("db");
+
+            db = (T) CallContext.GetData("db");
             return db;
         }
 
@@ -78,6 +79,7 @@ namespace Masuit.Tools.Net
             {
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
+
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
             if (string.IsNullOrEmpty(sessionKey))
             {
@@ -90,6 +92,7 @@ namespace Masuit.Tools.Net
             {
                 session[key] = obj;
             }
+
             try
             {
                 using (RedisHelper redisHelper = RedisHelper.GetInstance(1))
@@ -121,6 +124,7 @@ namespace Masuit.Tools.Net
             {
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
+
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
             if (string.IsNullOrEmpty(sessionKey))
             {
@@ -128,6 +132,7 @@ namespace Masuit.Tools.Net
                 HttpCookie cookie = new HttpCookie("SessionID", sessionKey);
                 HttpContext.Current.Response.Cookies.Add(cookie);
             }
+
             if (session != null)
             {
                 session[key] = obj;
@@ -157,7 +162,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
@@ -166,7 +171,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
@@ -204,6 +209,7 @@ namespace Masuit.Tools.Net
                                 redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
                                 return redisHelper.GetHash<T>(sessionKey, key);
                             }
+
                             return default(T);
                         }
                     }
@@ -212,8 +218,10 @@ namespace Masuit.Tools.Net
                         return default(T);
                     }
                 }
+
                 return obj;
             }
+
             return default(T);
         }
 
@@ -253,6 +261,7 @@ namespace Masuit.Tools.Net
                                 redisHelper.Expire(sessionKey, TimeSpan.FromMinutes(expire));
                                 return redisHelper.GetHash<T>(sessionKey, key);
                             }
+
                             return default(T);
                         }
                     }
@@ -261,8 +270,10 @@ namespace Masuit.Tools.Net
                         return default(T);
                     }
                 }
+
                 return obj;
             }
+
             return default(T);
         }
 
@@ -278,6 +289,7 @@ namespace Masuit.Tools.Net
             {
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
+
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
             if (!string.IsNullOrEmpty(sessionKey))
             {
@@ -316,6 +328,7 @@ namespace Masuit.Tools.Net
             {
                 throw new Exception("请确保此方法调用是在同步线程中执行!");
             }
+
             var sessionKey = HttpContext.Current.Request.Cookies["SessionID"]?.Value;
             if (!string.IsNullOrEmpty(sessionKey))
             {
@@ -362,6 +375,7 @@ namespace Masuit.Tools.Net
                 return 0;
             }
         }
+
         /// <summary>
         /// Session个数
         /// </summary>
@@ -382,6 +396,7 @@ namespace Masuit.Tools.Net
                 return 0;
             }
         }
+
         #endregion
 
         #region 获取客户端IP地址信息
@@ -403,8 +418,10 @@ namespace Masuit.Tools.Net
                     List<string> pois = address.AddressResult.Pois.Select(p => $"{p.AddressDetail}{p.Name} {p.Direction}{p.Distance ?? "0"}米").ToList();
                     return new Tuple<string, List<string>>(detail, pois);
                 }
+
                 return new Tuple<string, List<string>>("IP地址不正确", new List<string>());
             }
+
             return new Tuple<string, List<string>>($"{ip}不是一个合法的IP地址", new List<string>());
         }
 
@@ -423,7 +440,11 @@ namespace Masuit.Tools.Net
                 {
                     throw new Exception("未配置BaiduAK,请先在您的应用程序web.config或者App.config中的AppSettings节点下添加BaiduAK配置节(注意大小写)");
                 }
-                using (HttpClient client = new HttpClient() { BaseAddress = new Uri("http://api.map.baidu.com") })
+
+                using (HttpClient 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 =>
@@ -432,6 +453,7 @@ namespace Masuit.Tools.Net
                         {
                             return null;
                         }
+
                         var res = await t;
                         if (res.IsSuccessStatusCode)
                         {
@@ -448,7 +470,10 @@ namespace Masuit.Tools.Net
                             }
                             else
                             {
-                                using (var client2 = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") })
+                                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 =>
                                     {
@@ -456,6 +481,7 @@ namespace Masuit.Tools.Net
                                         {
                                             return null;
                                         }
+
                                         var result = await tt;
                                         if (result.IsSuccessStatusCode)
                                         {
@@ -477,16 +503,19 @@ namespace Masuit.Tools.Net
                                                 };
                                             }
                                         }
+
                                         return null;
                                     });
                                 }
                             }
                         }
+
                         return null;
                     });
                     return await await task;
                 }
             }
+
             return null;
         }
 
@@ -499,7 +528,10 @@ namespace Masuit.Tools.Net
         {
             if (ip.MatchInetAddress())
             {
-                using (var client = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") })
+                using (var client = new HttpClient
+                {
+                    BaseAddress = new Uri("http://ip.taobao.com")
+                })
                 {
                     var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
                     {
@@ -507,6 +539,7 @@ namespace Masuit.Tools.Net
                         {
                             return $"未能找到{ip}的ISP信息";
                         }
+
                         var result = await t;
                         if (result.IsSuccessStatusCode)
                         {
@@ -516,11 +549,13 @@ namespace Masuit.Tools.Net
                                 return taobaoIp.IpData.Isp;
                             }
                         }
+
                         return $"未能找到{ip}的ISP信息";
                     });
                     return task.Result.Result;
                 }
             }
+
             return $"{ip}不是一个合法的IP";
         }
 

+ 18 - 4
Masuit.Tools/NoSQL/RedisHelper.cs

@@ -59,6 +59,7 @@ namespace Masuit.Tools.NoSQL
         /// 静态连接池
         /// </summary>
         public static ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache { get; set; } = new ConcurrentDictionary<string, ConnectionMultiplexer>();
+
         #region 构造函数
 
         /// <summary>
@@ -188,8 +189,7 @@ namespace Masuit.Tools.NoSQL
         /// <returns>是否保存成功</returns>
         public bool SetString(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
         {
-            List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
-                keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
+            List<KeyValuePair<RedisKey, RedisValue>> newkeyValues = keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
             return Do(db => db.StringSet(newkeyValues.ToArray()));
         }
 
@@ -220,6 +220,7 @@ namespace Masuit.Tools.NoSQL
                 key = AddSysCustomKey(key);
                 return Do(db => db.StringGet(key));
             }
+
             return string.Empty;
         }
 
@@ -247,6 +248,7 @@ namespace Masuit.Tools.NoSQL
                 key = AddSysCustomKey(key);
                 return Do(db => ConvertObj<T>(db.StringGet(key)));
             }
+
             return default(T);
         }
 
@@ -298,8 +300,7 @@ namespace Masuit.Tools.NoSQL
         /// <returns>是否保存成功</returns>
         public async Task<bool> SetStringAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
         {
-            List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
-                keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
+            List<KeyValuePair<RedisKey, RedisValue>> newkeyValues = keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
             return await Do(async db => await db.StringSetAsync(newkeyValues.ToArray()));
         }
 
@@ -330,6 +331,7 @@ namespace Masuit.Tools.NoSQL
                 key = AddSysCustomKey(key);
                 return await Do(async db => await db.StringGetAsync(key));
             }
+
             return string.Empty;
         }
 
@@ -358,6 +360,7 @@ namespace Masuit.Tools.NoSQL
                 string result = await Do(async db => await db.StringGetAsync(key));
                 return ConvertObj<T>(result);
             }
+
             return default(T);
         }
 
@@ -482,6 +485,7 @@ namespace Masuit.Tools.NoSQL
                     return ConvertObj<T>(value);
                 });
             }
+
             return default(T);
         }
 
@@ -616,6 +620,7 @@ namespace Masuit.Tools.NoSQL
                 string value = await Do(async db => await db.HashGetAsync(key, dataKey));
                 return ConvertObj<T>(value);
             }
+
             return default(T);
         }
 
@@ -695,6 +700,7 @@ namespace Masuit.Tools.NoSQL
                     return ConvetList<T>(values);
                 });
             }
+
             return new List<T>();
         }
 
@@ -727,6 +733,7 @@ namespace Masuit.Tools.NoSQL
                     return ConvertObj<T>(value);
                 });
             }
+
             return default(T);
         }
 
@@ -759,6 +766,7 @@ namespace Masuit.Tools.NoSQL
                     return ConvertObj<T>(value);
                 });
             }
+
             return default(T);
         }
 
@@ -802,6 +810,7 @@ namespace Masuit.Tools.NoSQL
                 var values = await Do(async redis => await redis.ListRangeAsync(key));
                 return ConvetList<T>(values);
             }
+
             return new List<T>();
         }
 
@@ -831,6 +840,7 @@ namespace Masuit.Tools.NoSQL
                 var value = await Do(async db => await db.ListRightPopAsync(key));
                 return ConvertObj<T>(value);
             }
+
             return default(T);
         }
 
@@ -860,6 +870,7 @@ namespace Masuit.Tools.NoSQL
                 var value = await Do(async db => await db.ListLeftPopAsync(key));
                 return ConvertObj<T>(value);
             }
+
             return default(T);
         }
 
@@ -921,6 +932,7 @@ namespace Masuit.Tools.NoSQL
                     return ConvetList<T>(values);
                 });
             }
+
             return new List<T>();
         }
 
@@ -975,6 +987,7 @@ namespace Masuit.Tools.NoSQL
                 var values = await Do(async redis => await redis.SortedSetRangeByRankAsync(key));
                 return ConvetList<T>(values);
             }
+
             return new List<T>();
         }
 
@@ -1208,6 +1221,7 @@ namespace Masuit.Tools.NoSQL
                 var model = ConvertObj<T>(item);
                 result.Add(model);
             }
+
             return result;
         }
 

+ 35 - 10
Masuit.Tools/Reflection/ReflectHelper.cs

@@ -14,6 +14,7 @@ namespace Masuit.Tools.Reflection
     public static class ReflectHelper
     {
         #region 成员读写
+
         /// <summary>
         /// 获取实体相关属性的值
         /// </summary>
@@ -31,11 +32,14 @@ namespace Masuit.Tools.Reflection
                     objRet = descriptor.GetValue(obj);
                 }
             }
+
             return objRet;
         }
+
         #endregion
 
         #region 方法调用
+
         /// <summary>
         /// 直接调用内部对象的方法/函数或获取属性(支持重载调用)
         /// </summary>
@@ -53,6 +57,7 @@ namespace Masuit.Tools.Reflection
             {
                 throw new InvalidProgramException(string.Concat("函数/方法 [", funName, "] 在指定类型(", refType.ToString(), ")中不存在!"));
             }
+
             MethodInfo targetMethod = null;
             StringBuilder pb = new StringBuilder();
             foreach (MemberInfo mi in mis)
@@ -62,10 +67,13 @@ namespace Masuit.Tools.Reflection
                     if (mi.MemberType == MemberTypes.Property)
                     {
                         #region 调用属性方法Get
+
                         targetMethod = ((PropertyInfo)mi).GetGetMethod();
                         break;
+
                         #endregion
                     }
+
                     throw new InvalidProgramException(string.Concat("[", funName, "] 不是有效的函数/属性方法!"));
                 }
 
@@ -82,6 +90,7 @@ namespace Masuit.Tools.Reflection
                     int paramIdx = 0;
 
                     #region 检查数据类型 设置validParamsType是否有效
+
                     foreach (ParameterInfo pi in pis)
                     {
                         pb.AppendFormat("Parameter {0}: Type={1}, Name={2}\n", paramIdx, pi.ParameterType, pi.Name);
@@ -90,6 +99,7 @@ namespace Masuit.Tools.Reflection
                         if (funParams[paramIdx] != null && pi.ParameterType != typeof(object) && (pi.ParameterType != funParams[paramIdx].GetType()))
                         {
                             #region 检查类型是否兼容
+
                             try
                             {
                                 funParams[paramIdx] = Convert.ChangeType(funParams[paramIdx], pi.ParameterType);
@@ -98,11 +108,15 @@ namespace Masuit.Tools.Reflection
                             {
                                 paramFlag = false;
                             }
+
                             #endregion
+
                             //break;
                         }
+
                         ++paramIdx;
                     }
+
                     #endregion
 
                     bool validParamsType;
@@ -114,32 +128,38 @@ namespace Masuit.Tools.Reflection
                     {
                         continue;
                     }
+
                     if (validParamsLen && validParamsType)
                     {
                         targetMethod = curMethod;
                         break;
                     }
                 }
+
                 #endregion
             }
 
             if (targetMethod != null)
             {
-                object objReturn = null;
+                object objReturn;
+
                 #region 兼顾效率和兼容重载函数调用
+
                 try
                 {
                     object objInstance = Activator.CreateInstance(refType, objInitial);
-                    objReturn = targetMethod.Invoke(objInstance, BindingFlags.InvokeMethod, Type.DefaultBinder, funParams,
-                        System.Globalization.CultureInfo.InvariantCulture);
+                    objReturn = targetMethod.Invoke(objInstance, BindingFlags.InvokeMethod, Type.DefaultBinder, funParams, System.Globalization.CultureInfo.InvariantCulture);
                 }
                 catch (Exception)
                 {
                     objReturn = refType.InvokeMember(funName, BindingFlags.InvokeMethod, Type.DefaultBinder, null, funParams);
                 }
+
                 #endregion
+
                 return (T)objReturn;
             }
+
             throw new InvalidProgramException(string.Concat("函数/方法 [", refType.ToString(), ".", funName, "(args ...) ] 参数长度和数据类型不正确!\n 引用参数信息参考:\n", pb.ToString()));
         }
 
@@ -155,9 +175,11 @@ namespace Masuit.Tools.Reflection
         {
             return InvokeMethodOrGetProperty<T>(refType, funName, null, funParams);
         }
+
         #endregion
 
         #region 资源获取
+
         /// <summary>
         /// 获取程序集资源的位图资源
         /// </summary>
@@ -189,20 +211,23 @@ namespace Masuit.Tools.Reflection
         /// </summary>
         /// <param name="assemblyType">程序集中的某一对象类型</param>
         /// <param name="charset">字符集编码</param>
-        /// <param name="ResName">嵌入资源相对路径</param>
+        /// <param name="resName">嵌入资源相对路径</param>
         /// <returns>如没找到该资源则返回空字符</returns>
-        public static string GetManifestString(this Type assemblyType, string charset, string ResName)
+        public static string GetManifestString(this Type assemblyType, string charset, string resName)
         {
             Assembly asm = Assembly.GetAssembly(assemblyType);
-            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace,
-                ".", ResName.Replace("/", ".")));
-            if (st == null) { return ""; }
+            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
+            if (st == null)
+            {
+                return "";
+            }
+
             int iLen = (int)st.Length;
             byte[] bytes = new byte[iLen];
             st.Read(bytes, 0, iLen);
             return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
         }
-        #endregion
 
+        #endregion
     }
-}
+}

+ 30 - 27
Masuit.Tools/Reflection/ReflectionUtil.cs

@@ -14,6 +14,7 @@ namespace Masuit.Tools.Reflection
     public static class ReflectionUtil
     {
         #region 属性字段设置
+
 #pragma warning disable 1591
         public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
 #pragma warning restore 1591
@@ -139,19 +140,14 @@ namespace Masuit.Tools.Reflection
                 throw new ArgumentNullException(nameof(value));
             }
 
-            string text1;
-
             FieldInfo fi = value.GetType().GetField(value.ToString());
-
-            DescriptionAttribute[] attributes =
-                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
-
-            text1 = (attributes.Length > 0) ? attributes[0].Description : value.ToString();
-
+            DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
+            var text1 = (attributes.Length > 0) ? attributes[0].Description : value.ToString();
             if ((args != null) && (args.Length > 0))
             {
                 return string.Format(null, text1, args);
             }
+
             return text1;
         }
 
@@ -185,19 +181,19 @@ namespace Masuit.Tools.Reflection
 
             if (member.IsDefined(typeof(DescriptionAttribute), false))
             {
-                DescriptionAttribute[] attributes =
-                    (DescriptionAttribute[])member.GetCustomAttributes(typeof(DescriptionAttribute), false);
+                DescriptionAttribute[] attributes = (DescriptionAttribute[]) member.GetCustomAttributes(typeof(DescriptionAttribute), false);
                 text1 = attributes[0].Description;
             }
             else
             {
-                return System.String.Empty;
+                return string.Empty;
             }
 
             if ((args != null) && (args.Length > 0))
             {
-                return System.String.Format(null, text1, args);
+                return string.Format(null, text1, args);
             }
+
             return text1;
         }
 
@@ -221,15 +217,18 @@ namespace Masuit.Tools.Reflection
             {
                 throw new ArgumentNullException(nameof(attributeType));
             }
+
             if (assembly == null)
             {
                 throw new ArgumentNullException(nameof(assembly));
             }
+
             if (assembly.IsDefined(attributeType, false))
             {
                 object[] attributes = assembly.GetCustomAttributes(attributeType, false);
                 return attributes[0];
             }
+
             return null;
         }
 
@@ -255,18 +254,16 @@ namespace Masuit.Tools.Reflection
         /// </returns>
         public static object GetAttribute(this Type attributeType, MemberInfo type, bool searchParent)
         {
-            if (attributeType == null)
-            {
-                return null;
-            }
             if (type == null)
             {
                 return null;
             }
+
             if (!(attributeType.IsSubclassOf(typeof(Attribute))))
             {
                 return null;
             }
+
             if (type.IsDefined(attributeType, searchParent))
             {
                 object[] attributes = type.GetCustomAttributes(attributeType, searchParent);
@@ -276,6 +273,7 @@ namespace Masuit.Tools.Reflection
                     return attributes[0];
                 }
             }
+
             return null;
         }
 
@@ -305,18 +303,17 @@ namespace Masuit.Tools.Reflection
             {
                 return null;
             }
-            if (attributeType == null)
-            {
-                return null;
-            }
+
             if (!(attributeType.IsSubclassOf(typeof(Attribute))))
             {
                 return null;
             }
+
             if (type.IsDefined(attributeType, false))
             {
                 return type.GetCustomAttributes(attributeType, searchParent);
             }
+
             return null;
         }
 
@@ -346,7 +343,7 @@ namespace Masuit.Tools.Reflection
         {
             Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
             ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
-            return (Bitmap)rm.GetObject(imageName);
+            return (Bitmap) rm.GetObject(imageName);
         }
 
         /// <summary>
@@ -367,15 +364,18 @@ namespace Masuit.Tools.Reflection
         /// </summary>
         /// <param name="assemblyType">程序集中的某一对象类型</param>
         /// <param name="charset">字符集编码</param>
-        /// <param name="ResName">嵌入资源相对路径</param>
+        /// <param name="resName">嵌入资源相对路径</param>
         /// <returns>如没找到该资源则返回空字符</returns>
-        public static string GetManifestString(this Type assemblyType, string charset, string ResName)
+        public static string GetManifestString(this Type assemblyType, string charset, string resName)
         {
             Assembly asm = Assembly.GetAssembly(assemblyType);
-            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace,
-                ".", ResName.Replace("/", ".")));
-            if (st == null) { return ""; }
-            int iLen = (int)st.Length;
+            Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
+            if (st == null)
+            {
+                return "";
+            }
+
+            int iLen = (int) st.Length;
             byte[] bytes = new byte[iLen];
             st.Read(bytes, 0, iLen);
             return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
@@ -384,6 +384,7 @@ namespace Masuit.Tools.Reflection
         #endregion
 
         #region 创建对应实例
+
         /// <summary>
         /// 创建对应实例
         /// </summary>
@@ -400,6 +401,7 @@ namespace Masuit.Tools.Reflection
                     return t.CreateInstance(type) as T;
                 }
             }
+
             return null;
             //return Assembly.GetExecutingAssembly().CreateInstance(type);
         }
@@ -413,6 +415,7 @@ namespace Masuit.Tools.Reflection
         {
             return CreateInstance<T>(type.FullName);
         }
+
         #endregion
     }
 }

文件差異過大導致無法顯示
+ 331 - 246
Masuit.Tools/Security/Encrypt.cs


+ 4 - 3
Masuit.Tools/Security/HashEncode.cs

@@ -1,7 +1,7 @@
-using System;
+using Masuit.Tools.Win32;
+using System;
 using System.Security.Cryptography;
 using System.Text;
-using Masuit.Tools.Win32;
 
 namespace Masuit.Tools.Security
 {
@@ -32,7 +32,8 @@ namespace Masuit.Tools.Security
             {
                 sb.Append((int)o + "O");
             }
+
             return sb.ToString();
         }
     }
-}
+}

+ 6 - 1
Masuit.Tools/Security/RSACrypt.cs

@@ -20,6 +20,7 @@ namespace Masuit.Tools.Security
         /// </summary>
         public string PrivateKey;
     }
+
     /// <summary> 
     /// RSA加密解密及RSA签名和验证
     /// </summary> 
@@ -36,7 +37,11 @@ namespace Masuit.Tools.Security
         {
             using (var rsa = new RSACryptoServiceProvider())
             {
-                return new RsaKey { PrivateKey = rsa.ToXmlString(true), PublicKey = rsa.ToXmlString(false) };
+                return new RsaKey
+                {
+                    PrivateKey = rsa.ToXmlString(true),
+                    PublicKey = rsa.ToXmlString(false)
+                };
             }
         }
 

+ 13 - 6
Masuit.Tools/Strings/ValidateCode.cs

@@ -30,7 +30,7 @@ namespace Masuit.Tools.Strings
             {
                 sb.Append(ch[r.Next(ch.Length)]);
             }
-            r = null;
+
             return sb.ToString();
         }
 
@@ -45,7 +45,7 @@ namespace Masuit.Tools.Strings
         /// <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)
         {
-            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))
                 {
@@ -62,10 +62,17 @@ namespace Masuit.Tools.Strings
                         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) };
+
+                    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);
+                    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);
 
                     //画图片的前景干扰点
@@ -75,6 +82,7 @@ namespace Masuit.Tools.Strings
                         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);
                     //保存图片数据
@@ -87,6 +95,5 @@ namespace Masuit.Tools.Strings
                 }
             }
         }
-
     }
 }

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

@@ -32,6 +32,7 @@ namespace Masuit.Tools.Systems
                 names = GetDictionaryItems(enumType);
                 EnumNameValueDict[enumType] = names;
             }
+
             return names;
         }
 
@@ -41,9 +42,10 @@ 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;
             }
+
             return names;
         }
 
@@ -61,6 +63,7 @@ namespace Masuit.Tools.Systems
                 values = GetValueNameItems(enumType);
                 EnumValueNameDict[enumType] = values;
             }
+
             return values;
         }
 
@@ -70,8 +73,9 @@ 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;
         }
 
@@ -102,6 +106,7 @@ namespace Masuit.Tools.Systems
             {
                 return _enumTypeDict[typeName];
             }
+
             return null;
         }
 
@@ -122,8 +127,9 @@ 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;
         }
 
@@ -143,6 +149,7 @@ namespace Masuit.Tools.Systems
                     return attrs[0].Description; //返回当前描述  
                 }
             }
+
             return en.ToString();
         }
 
@@ -162,6 +169,7 @@ namespace Masuit.Tools.Systems
                     return attrs[0].Name; //返回当前描述  
                 }
             }
+
             return en.ToString();
         }
 
@@ -190,11 +198,12 @@ 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);
                 }
             }
+
             return nvc;
         }
     }
-}
+}

+ 34 - 9
Masuit.Tools/Systems/RedisLock.cs

@@ -10,11 +10,14 @@ namespace Masuit.Tools.Systems
     public class RedisLock : IDisposable
     {
         #region Property
-        private bool isDisposed;
+
+        private bool _isDisposed;
+
         ~RedisLock()
         {
             Dispose(false);
         }
+
         /// <summary>
         /// KEYS[1] :需要加锁的key,这里需要是字符串类型。
         /// ARGV[1] :锁的超时时间,防止死锁
@@ -75,6 +78,7 @@ namespace Masuit.Tools.Systems
         #endregion
 
         #region Constructor
+
         /// <summary>
         /// 默认连接127.0.0.1:6379,synctimeout=20000
         /// </summary>
@@ -164,10 +168,23 @@ namespace Masuit.Tools.Systems
         /// <returns></returns>
         public RedisResult UnLock(Lock lockObject)
         {
-            if (lockObject == null) return null;
+            if (lockObject == null)
+            {
+                return null;
+            }
+
             CancelExpirationRenewal(lockObject);
-            RedisKey[] key = { lockObject.Resource, GetChannelName(lockObject.Resource) };
-            RedisValue[] values = { Thread.CurrentThread.ManagedThreadId, 10000, lockObject.Value };
+            RedisKey[] key =
+            {
+                lockObject.Resource,
+                GetChannelName(lockObject.Resource)
+            };
+            RedisValue[] values =
+            {
+                Thread.CurrentThread.ManagedThreadId,
+                10000,
+                lockObject.Value
+            };
             return _server.GetDatabase().ScriptEvaluate(UnLockScript, key, values);
         }
 
@@ -210,8 +227,15 @@ namespace Masuit.Tools.Systems
 
         private RedisResult LockInnerAsync(RedisKey resource, TimeSpan waitTime, string threadId)
         {
-            RedisKey[] key = { resource };
-            RedisValue[] values = { waitTime.TotalMilliseconds, threadId };
+            RedisKey[] key =
+            {
+                resource
+            };
+            RedisValue[] values =
+            {
+                waitTime.TotalMilliseconds,
+                threadId
+            };
             return _server.GetDatabase().ScriptEvaluate(LockScript, key, values);
         }
 
@@ -239,7 +263,7 @@ namespace Masuit.Tools.Systems
         protected CancellationTokenSource TaskTimeOut(Func<Lock, bool> action, Lock lockObj, int time)
         {
             var timeoutCancellationTokenSource = new CancellationTokenSource();
-            var task = Task.Run(() =>
+            Task.Run(() =>
             {
                 SpinWait.SpinUntil(() => !timeoutCancellationTokenSource.IsCancellationRequested);
             }, timeoutCancellationTokenSource.Token);
@@ -288,12 +312,13 @@ namespace Masuit.Tools.Systems
 
         public virtual void Dispose(bool disposing)
         {
-            if (isDisposed)
+            if (_isDisposed)
             {
                 return;
             }
+
             _server?.Dispose();
-            isDisposed = true;
+            _isDisposed = true;
             //_server = null;
         }
     }

+ 36 - 19
Masuit.Tools/Win32/Windows.cs

@@ -1,4 +1,5 @@
-using System;
+using Masuit.Tools.Hardware;
+using System;
 using System.Diagnostics;
 using System.Management;
 using System.Net;
@@ -6,7 +7,7 @@ using System.Runtime.InteropServices;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading;
-using Masuit.Tools.Hardware;
+using static System.String;
 
 namespace Masuit.Tools.Win32
 {
@@ -50,6 +51,7 @@ namespace Masuit.Tools.Win32
                         //两个系统的关键进程,不整理
                         continue;
                     }
+
                     try
                     {
                         EmptyWorkingSet(p.Handle);
@@ -74,6 +76,7 @@ namespace Masuit.Tools.Win32
             {
                 return m.Groups[2].Value;
             }
+
             try
             {
                 string ip;
@@ -82,6 +85,7 @@ namespace Masuit.Tools.Win32
                     c.Connect("www.baidu.com", 80);
                     ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                 }
+
                 return ip;
             }
             catch (Exception)
@@ -108,7 +112,8 @@ namespace Masuit.Tools.Win32
 
                 Process proc = new Process
                 {
-                    StartInfo = {
+                    StartInfo =
+                    {
                         FileName = filename,
                         CreateNoWindow = true,
                         Arguments = arguments,
@@ -121,12 +126,14 @@ namespace Masuit.Tools.Win32
                 using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
                 {
                     //上面标记的是原文,下面是我自己调试错误后自行修改的  
-                    Thread.Sleep(100);           //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
-                                                 //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
-                    if (!proc.HasExited)         //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
-                    {                            //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
+                    Thread.Sleep(100); //貌似调用系统的nslookup还未返回数据或者数据未编码完成,程序就已经跳过直接执行  
+                    //txt = sr.ReadToEnd()了,导致返回的数据为空,故睡眠令硬件反应  
+                    if (!proc.HasExited) //在无参数调用nslookup后,可以继续输入命令继续操作,如果进程未停止就直接执行  
+                    {
+                        //txt = sr.ReadToEnd()程序就在等待输入,而且又无法输入,直接掐住无法继续运行  
                         proc.Kill();
                     }
+
                     string txt = sr.ReadToEnd();
                     if (recordLog)
                         Trace.WriteLine(txt);
@@ -249,6 +256,7 @@ namespace Masuit.Tools.Win32
                         }
                     }
                 }
+
                 return cpuInfo;
             }
             catch
@@ -277,6 +285,7 @@ namespace Masuit.Tools.Win32
             {
                 // ignored
             }
+
             return -1;
         }
 
@@ -290,7 +299,7 @@ namespace Masuit.Tools.Win32
             {
                 using (ManagementObjectCollection cpus = mc.GetInstances())
                 {
-                    var MHz = new string[cpus.Count];
+                    var mhz = new string[cpus.Count];
                     int c = 0;
                     using (var mySearch = new ManagementObjectSearcher("select * from Win32_Processor"))
                     {
@@ -298,12 +307,13 @@ namespace Masuit.Tools.Win32
                         {
                             using (mo)
                             {
-                                MHz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
+                                mhz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
                                 c++;
                             }
                         }
                     }
-                    return MHz;
+
+                    return mhz;
                 }
             }
         }
@@ -324,6 +334,7 @@ namespace Masuit.Tools.Win32
                     }
                 }
             }
+
             return "-1";
         }
 
@@ -339,7 +350,7 @@ namespace Masuit.Tools.Win32
                     {
                         using (mo)
                         {
-                            if ((bool)mo["IPEnabled"] == true)
+                            if ((bool)mo["IPEnabled"])
                             {
                                 mac = mo["MacAddress"].ToString();
                                 break;
@@ -347,6 +358,7 @@ namespace Masuit.Tools.Win32
                         }
                     }
                 }
+
                 return mac;
             }
             catch
@@ -360,14 +372,14 @@ namespace Masuit.Tools.Win32
             try
             {
                 //获取IP地址 
-                string st = String.Empty;
+                string st = Empty;
                 using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                 {
                     foreach (ManagementObject mo in mc.GetInstances())
                     {
                         using (mo)
                         {
-                            if ((bool)mo["IPEnabled"] == true)
+                            if ((bool)mo["IPEnabled"])
                             {
                                 //st=mo[ "IpAddress "].ToString(); 
                                 Array ar;
@@ -378,6 +390,7 @@ namespace Masuit.Tools.Win32
                         }
                     }
                 }
+
                 return st;
             }
             catch
@@ -391,18 +404,19 @@ namespace Masuit.Tools.Win32
             try
             {
                 //获取硬盘ID 
-                string HDid = String.Empty;
+                string hdid = Empty;
                 using (var mc = new ManagementClass("Win32_DiskDrive"))
                 {
                     foreach (ManagementObject mo in mc.GetInstances())
                     {
                         using (mo)
                         {
-                            HDid = (string)mo.Properties["Model"].Value;
+                            hdid = (string)mo.Properties["Model"].Value;
                         }
                     }
                 }
-                return HDid;
+
+                return hdid;
             }
             catch
             {
@@ -418,7 +432,7 @@ namespace Masuit.Tools.Win32
         {
             try
             {
-                string st = String.Empty;
+                string st = Empty;
                 using (var mc = new ManagementClass("Win32_ComputerSystem"))
                 {
                     foreach (ManagementObject mo in mc.GetInstances())
@@ -429,6 +443,7 @@ namespace Masuit.Tools.Win32
                         }
                     }
                 }
+
                 return st;
             }
             catch
@@ -441,7 +456,7 @@ namespace Masuit.Tools.Win32
         {
             try
             {
-                string st = String.Empty;
+                string st = Empty;
                 using (var mc = new ManagementClass("Win32_ComputerSystem"))
                 {
                     foreach (var o in mc.GetInstances())
@@ -453,6 +468,7 @@ namespace Masuit.Tools.Win32
                         }
                     }
                 }
+
                 return st;
             }
             catch
@@ -465,7 +481,7 @@ namespace Masuit.Tools.Win32
         {
             try
             {
-                string st = String.Empty;
+                string st = Empty;
                 using (var mc = new ManagementClass("Win32_ComputerSystem"))
                 {
                     using (ManagementObjectCollection moc = mc.GetInstances())
@@ -478,6 +494,7 @@ namespace Masuit.Tools.Win32
                         }
                     }
                 }
+
                 return st;
             }
             catch

+ 3 - 1
Masuit.Tools/Win32/WindowsCommand.cs

@@ -10,7 +10,6 @@ namespace Masuit.Tools.Win32
     /// </summary>
     public static class WindowsCommand
     {
-
         /// <summary>
         /// 生成真正的随机数
         /// </summary>
@@ -75,11 +74,14 @@ namespace Masuit.Tools.Win32
                         {
                             process.WaitForExit(outtime);
                         }
+
                         output = process.StandardOutput.ReadToEnd(); //读取进程的输出  
                     }
                 }
+
                 return output;
             }
+
             throw new Exception("命令参数无效,必须传入一个控制台能被cmd.exe可执行程序;\n如:ping 127.0.0.1");
         }
     }

+ 26 - 30
Test/Program.cs

@@ -1,8 +1,5 @@
-using System;
-using System.Collections.Concurrent;
-using System.Threading.Tasks;
-using Masuit.Tools;
-using Masuit.Tools.Systems;
+using Masuit.Tools.DateTimeExt;
+using System;
 
 namespace Test
 {
@@ -10,32 +7,31 @@ namespace Test
     {
         static void Main(string[] args)
         {
-            Console.WriteLine("".CreateShortToken(26));
-            //var redisLock = new RedisLock();
-        }
+            //DateTime dt = DateTime.Parse("2019-2-6");
+            //ChineseCalendar.SolarHolidayInfo.Add(new DateInfoStruct(12, 31, 1, "元旦"));
+            //ChineseCalendar cc = new ChineseCalendar(dt);
+            //Console.WriteLine("阳历:" + cc.DateString);
+            //Console.WriteLine("属相:" + cc.AnimalString);
+            //Console.WriteLine("农历:" + cc.ChineseDateString);
+            //Console.WriteLine("时辰:" + cc.ChineseHour);
+            //Console.WriteLine("节气:" + cc.ChineseTwentyFourDay);
+            //Console.WriteLine("节日:" + cc.DateHoliday);
+            //Console.WriteLine("农历节日:" + cc.ChineseCalendarHoliday);
+            //Console.WriteLine("前一个节气:" + cc.ChineseTwentyFourPrevDay);
+            //Console.WriteLine("后一个节气:" + cc.ChineseTwentyFourNextDay);
+            //Console.WriteLine("干支:" + cc.GanZhiDateString);
+            //Console.WriteLine("星期:" + cc.WeekDayStr);
+            //Console.WriteLine("星宿:" + cc.ChineseConstellation);
+            //Console.WriteLine("星座:" + cc.Constellation);
+            //Console.WriteLine("是否是假期:" + cc.IsHoliday);
+            //Console.WriteLine("是否是工作日:" + cc.IsWorkDay);
 
-        public static ConcurrentDictionary<string, object> LockDic { get; set; } = new ConcurrentDictionary<string, object>();
-        public static int Count { get; set; }
-        public static async Task<string> Test()
-        {
-            //using (new AsyncLock(LockDic.GetOrAdd("aa", new object())).LockAsync())
-            {
-                await Task.Run(() =>
-                {
-                    for (int i = 0; i < 100; i++)
-                    {
-                        Count++;
-                    }
-                });
-                await Task.Run(() =>
-                {
-                    for (int i = 0; i < 100; i++)
-                    {
-                        Count--;
-                    }
-                });
-                return "";
-            }
+            DateTime today = DateTime.Parse("2019-1-1");
+            var cc = new ChineseCalendar(today);
+            var ccEnd = cc.AddWorkDays(30);
+            var endDate = ccEnd.Date;
+            Console.WriteLine((endDate - today).TotalDays);
         }
     }
+
 }

+ 5 - 0
Test/Test.csproj

@@ -21,6 +21,8 @@
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>..\..\..\Company\XiLife.NDC.WebAPI\XiLife.NDC.WebAPI\CodeRules\XiLife.ITC.Rules.CSharp.ruleset</CodeAnalysisRuleSet>
+    <RunCodeAnalysis>true</RunCodeAnalysis>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <PlatformTarget>AnyCPU</PlatformTarget>
@@ -30,6 +32,8 @@
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <RunCodeAnalysis>true</RunCodeAnalysis>
+    <CodeAnalysisRuleSet>..\..\..\Company\XiLife.NDC.WebAPI\XiLife.NDC.WebAPI\CodeRules\XiLife.ITC.Rules.CSharp.ruleset</CodeAnalysisRuleSet>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="DnsClient, Version=1.2.0.0, Culture=neutral, PublicKeyToken=4574bb5573c51424, processorArchitecture=MSIL">
@@ -74,6 +78,7 @@
   <ItemGroup>
     <None Include="App.config" />
     <None Include="packages.config" />
+    <None Include="Test.ruleset" />
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\Masuit.Tools.NoSQL.MongoDBClient\Masuit.Tools.NoSQL.MongoDBClient.csproj">

+ 68 - 0
Test/Test.ruleset

@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RuleSet Name="Test 的规则" Description="Test.csproj 的代码分析规则。" ToolsVersion="15.0">
+  <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
+    <Rule Id="CA1001" Action="Warning" />
+    <Rule Id="CA1009" Action="Warning" />
+    <Rule Id="CA1016" Action="Warning" />
+    <Rule Id="CA1033" Action="Warning" />
+    <Rule Id="CA1049" Action="Warning" />
+    <Rule Id="CA1060" Action="Warning" />
+    <Rule Id="CA1061" Action="Warning" />
+    <Rule Id="CA1063" Action="Warning" />
+    <Rule Id="CA1065" Action="Warning" />
+    <Rule Id="CA1301" Action="Warning" />
+    <Rule Id="CA1400" Action="Warning" />
+    <Rule Id="CA1401" Action="Warning" />
+    <Rule Id="CA1403" Action="Warning" />
+    <Rule Id="CA1404" Action="Warning" />
+    <Rule Id="CA1405" Action="Warning" />
+    <Rule Id="CA1410" Action="Warning" />
+    <Rule Id="CA1415" Action="Warning" />
+    <Rule Id="CA1502" Action="Error" />
+    <Rule Id="CA1821" Action="Warning" />
+    <Rule Id="CA1900" Action="Warning" />
+    <Rule Id="CA1901" Action="Warning" />
+    <Rule Id="CA2002" Action="Warning" />
+    <Rule Id="CA2100" Action="Warning" />
+    <Rule Id="CA2101" Action="Warning" />
+    <Rule Id="CA2108" Action="Warning" />
+    <Rule Id="CA2111" Action="Warning" />
+    <Rule Id="CA2112" Action="Warning" />
+    <Rule Id="CA2114" Action="Warning" />
+    <Rule Id="CA2116" Action="Warning" />
+    <Rule Id="CA2117" Action="Warning" />
+    <Rule Id="CA2122" Action="Warning" />
+    <Rule Id="CA2123" Action="Warning" />
+    <Rule Id="CA2124" Action="Warning" />
+    <Rule Id="CA2126" Action="Warning" />
+    <Rule Id="CA2131" Action="Warning" />
+    <Rule Id="CA2132" Action="Warning" />
+    <Rule Id="CA2133" Action="Warning" />
+    <Rule Id="CA2134" Action="Warning" />
+    <Rule Id="CA2137" Action="Warning" />
+    <Rule Id="CA2138" Action="Warning" />
+    <Rule Id="CA2140" Action="Warning" />
+    <Rule Id="CA2141" Action="Warning" />
+    <Rule Id="CA2146" Action="Warning" />
+    <Rule Id="CA2147" Action="Warning" />
+    <Rule Id="CA2149" Action="Warning" />
+    <Rule Id="CA2200" Action="Warning" />
+    <Rule Id="CA2202" Action="Warning" />
+    <Rule Id="CA2207" Action="Warning" />
+    <Rule Id="CA2212" Action="Warning" />
+    <Rule Id="CA2213" Action="Warning" />
+    <Rule Id="CA2214" Action="Warning" />
+    <Rule Id="CA2216" Action="Warning" />
+    <Rule Id="CA2220" Action="Warning" />
+    <Rule Id="CA2229" Action="Warning" />
+    <Rule Id="CA2231" Action="Warning" />
+    <Rule Id="CA2232" Action="Warning" />
+    <Rule Id="CA2235" Action="Warning" />
+    <Rule Id="CA2236" Action="Warning" />
+    <Rule Id="CA2237" Action="Warning" />
+    <Rule Id="CA2238" Action="Warning" />
+    <Rule Id="CA2240" Action="Warning" />
+    <Rule Id="CA2241" Action="Warning" />
+    <Rule Id="CA2242" Action="Warning" />
+  </Rules>
+</RuleSet>

部分文件因文件數量過多而無法顯示