Browse Source

添加项目文件。

懒得勤快 8 years ago
parent
commit
e945ccb48d
54 changed files with 15428 additions and 0 deletions
  1. 40 0
      Masuit.Tools.sln
  2. 67 0
      Masuit.Tools/Database/DataExt.cs
  3. 401 0
      Masuit.Tools/Database/DataTableHelper.cs
  4. 417 0
      Masuit.Tools/DateTimeExt/CCalendarData.xml
  5. 980 0
      Masuit.Tools/DateTimeExt/CNCalendar.cs
  6. 178 0
      Masuit.Tools/DateTimeExt/ChineseCalendar.cs
  7. 152 0
      Masuit.Tools/DateTimeExt/DateTimeHelper.cs
  8. 406 0
      Masuit.Tools/DateTimeExt/DateUtil.cs
  9. 475 0
      Masuit.Tools/DateTimeExt/TimeHelper.cs
  10. 400 0
      Masuit.Tools/Files/Compress.cs
  11. 143 0
      Masuit.Tools/Files/DocumentConvert.cs
  12. 60 0
      Masuit.Tools/Files/ExtensionAttach.cs
  13. 178 0
      Masuit.Tools/Files/FileExt.cs
  14. 152 0
      Masuit.Tools/Files/FileTree.cs
  15. 89 0
      Masuit.Tools/Files/INIFile.cs
  16. 467 0
      Masuit.Tools/Hardware/SystemInfo.cs
  17. 865 0
      Masuit.Tools/Html/HtmlHelper.cs
  18. 432 0
      Masuit.Tools/Html/HtmlPager.cs
  19. 53 0
      Masuit.Tools/Html/HtmlTools.cs
  20. 1573 0
      Masuit.Tools/Html/HtmlUtils.cs
  21. 235 0
      Masuit.Tools/Html/ListBuilder.cs
  22. 156 0
      Masuit.Tools/Masuit.Tools.csproj
  23. 1251 0
      Masuit.Tools/Media/ImageUtilities.cs
  24. 176 0
      Masuit.Tools/Models/AsposeLicense.cs
  25. 15 0
      Masuit.Tools/Models/Email.cs
  26. 10 0
      Masuit.Tools/Models/INetAddress.cs
  27. 21 0
      Masuit.Tools/Models/IPData.cs
  28. 129 0
      Masuit.Tools/Net/CacheHelper.cs
  29. 507 0
      Masuit.Tools/Net/CookieHelper.cs
  30. 332 0
      Masuit.Tools/Net/RedisHelper.cs
  31. 561 0
      Masuit.Tools/Net/SocketClient.cs
  32. 165 0
      Masuit.Tools/Net/WebExtension.cs
  33. 39 0
      Masuit.Tools/Properties/AssemblyInfo.cs
  34. 220 0
      Masuit.Tools/Reflection/ReflectHelper.cs
  35. 418 0
      Masuit.Tools/Reflection/ReflectionUtil.cs
  36. 544 0
      Masuit.Tools/Security/AESEncode.cs
  37. 1053 0
      Masuit.Tools/Security/Encrypt.cs
  38. 60 0
      Masuit.Tools/Security/HashEncode.cs
  39. 393 0
      Masuit.Tools/Security/RSACryption.cs
  40. 334 0
      Masuit.Tools/Strings/ConvertJson.cs
  41. 187 0
      Masuit.Tools/Strings/JsonHelper.cs
  42. 676 0
      Masuit.Tools/Strings/StringExt.cs
  43. 146 0
      Masuit.Tools/Strings/ValidateCode.cs
  44. 11 0
      Masuit.Tools/app.config
  45. 14 0
      Masuit.Tools/packages.config
  46. 2 0
      Masuit.Tools帮助文档/ContentLayout.content
  47. BIN
      Masuit.Tools帮助文档/Help/Masuit.Tools帮助文档.chm
  48. 74 0
      Masuit.Tools帮助文档/Masuit.Tools帮助文档.shfbproj
  49. BIN
      Masuit.Tools帮助文档/icons/Help.png
  50. 44 0
      MasuitTools/MasuitTools.nuproj
  51. 6 0
      Test/App.config
  52. 20 0
      Test/Program.cs
  53. 36 0
      Test/Properties/AssemblyInfo.cs
  54. 65 0
      Test/Test.csproj

+ 40 - 0
Masuit.Tools.sln

@@ -0,0 +1,40 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.25420.1
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masuit.Tools", "Masuit.Tools\Masuit.Tools.csproj", "{275D5A0D-C49C-497E-A4B5-F40285C2495F}"
+EndProject
+Project("{FF286327-C783-4F7A-AB73-9BCBAD0D4460}") = "MasuitTools", "MasuitTools\MasuitTools.nuproj", "{EB6CC774-090E-4102-A8B2-D8E11EBEBDD7}"
+EndProject
+Project("{7CF6DF6D-3B04-46F8-A40B-537D21BCA0B4}") = "Masuit.Tools帮助文档", "Masuit.Tools帮助文档\Masuit.Tools帮助文档.shfbproj", "{9960A20A-7BAD-4125-B93C-BCA3906EBCC1}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{06A73840-0809-4747-9760-7EF65A284C2B}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{275D5A0D-C49C-497E-A4B5-F40285C2495F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{275D5A0D-C49C-497E-A4B5-F40285C2495F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{275D5A0D-C49C-497E-A4B5-F40285C2495F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{275D5A0D-C49C-497E-A4B5-F40285C2495F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{EB6CC774-090E-4102-A8B2-D8E11EBEBDD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{EB6CC774-090E-4102-A8B2-D8E11EBEBDD7}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{EB6CC774-090E-4102-A8B2-D8E11EBEBDD7}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{EB6CC774-090E-4102-A8B2-D8E11EBEBDD7}.Release|Any CPU.Build.0 = Release|Any CPU
+		{9960A20A-7BAD-4125-B93C-BCA3906EBCC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{9960A20A-7BAD-4125-B93C-BCA3906EBCC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{9960A20A-7BAD-4125-B93C-BCA3906EBCC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{9960A20A-7BAD-4125-B93C-BCA3906EBCC1}.Release|Any CPU.Build.0 = Release|Any CPU
+		{06A73840-0809-4747-9760-7EF65A284C2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{06A73840-0809-4747-9760-7EF65A284C2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{06A73840-0809-4747-9760-7EF65A284C2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{06A73840-0809-4747-9760-7EF65A284C2B}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal

+ 67 - 0
Masuit.Tools/Database/DataExt.cs

@@ -0,0 +1,67 @@
+using System;
+using System.Data;
+using System.Data.SqlClient;
+using System.Reflection;
+
+namespace Masuit.Tools.Database
+{
+    /// <summary>
+    /// 日期操作扩展类
+    /// </summary>
+    public static class DataExt
+    {
+        /// <summary>
+        /// 根据SqlDataReader映射到实体模型
+        /// </summary>
+        /// <typeparam name="T">实体模型</typeparam>
+        /// <param name="reader">SqlDataReader</param>
+        /// <returns>映射后的实体模型</returns>
+        public static T MapEntity<T>(this SqlDataReader reader) where T : class
+        {
+            T obj = Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).FullName) as T;
+            Type type = typeof(T);
+            PropertyInfo[] properties = type.GetProperties();
+            foreach (PropertyInfo p in properties)
+            {
+                p.SetValue(obj, reader[p.Name]);
+            }
+            return obj;
+        }
+
+        /// <summary>
+        /// 根据DataRow映射到实体模型
+        /// </summary>
+        /// <typeparam name="T">实体模型</typeparam>
+        /// <param name="row">数据行</param>
+        /// <returns>映射后的实体模型</returns>
+        public static T MapEntity<T>(this DataRow row) where T : class
+        {
+            T obj = Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).FullName) as T;
+            Type type = typeof(T);
+            PropertyInfo[] properties = type.GetProperties();
+            foreach (PropertyInfo p in properties)
+            {
+                p.SetValue(obj, row[p.Name]);
+            }
+            return obj;
+        }
+
+        /// <summary>
+        /// 根据DataReader映射到实体模型
+        /// </summary>
+        /// <typeparam name="T">实体模型</typeparam>
+        /// <param name="dr">IDataReader</param>
+        /// <returns>映射后的实体模型</returns>
+        public static T MapEntity<T>(this IDataReader dr) where T : class
+        {
+            T obj = Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).FullName) as T;
+            Type type = typeof(T);
+            PropertyInfo[] properties = type.GetProperties();
+            foreach (PropertyInfo p in properties)
+            {
+                p.SetValue(obj, dr[p.Name]);
+            }
+            return obj;
+        }
+    }
+}

+ 401 - 0
Masuit.Tools/Database/DataTableHelper.cs

@@ -0,0 +1,401 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Data;
+using System.Reflection;
+
+namespace Masuit.Tools.Database
+{
+    /// <summary>
+    /// DataTable帮助类
+    /// </summary>
+    public static class DataTableHelper
+    {
+        /// <summary>
+        /// 给DataTable增加一个自增列
+        /// 如果DataTable 存在 identityid 字段  则 直接返回DataTable 不做任何处理
+        /// </summary>
+        /// <param name="dt">DataTable</param>
+        /// <returns>返回Datatable 增加字段 identityid </returns>
+        public static DataTable AddIdentityColumn(DataTable dt)
+        {
+            if (!dt.Columns.Contains("identityid"))
+            {
+                dt.Columns.Add("identityid");
+                for (int i = 0; i < dt.Rows.Count; i++)
+                {
+                    dt.Rows[i]["identityid"] = (i + 1).ToString();
+                }
+            }
+            return dt;
+        }
+
+        /// <summary>
+        /// 检查DataTable 是否有数据行
+        /// </summary>
+        /// <param name="dt">DataTable</param>
+        /// <returns>是否有数据行</returns>
+        public static bool IsHaveRows(DataTable dt)
+        {
+            if (dt?.Rows.Count > 0)
+                return true;
+
+            return false;
+        }
+
+        /// <summary>
+        /// DataTable转换成实体列表
+        /// </summary>
+        /// <typeparam name="T">实体 T </typeparam>
+        /// <param name="table">datatable</param>
+        /// <returns>强类型的数据集合</returns>
+        public static IList<T> DataTableToList<T>(DataTable table)
+            where T : class
+        {
+            if (!IsHaveRows(table))
+                return new List<T>();
+
+            IList<T> list = new List<T>();
+            T model = default(T);
+            foreach (DataRow dr in table.Rows)
+            {
+                model = Activator.CreateInstance<T>();
+
+                foreach (DataColumn dc in dr.Table.Columns)
+                {
+                    object drValue = dr[dc.ColumnName];
+                    PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
+
+                    if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
+                    {
+                        pi.SetValue(model, drValue, null);
+                    }
+                }
+
+                list.Add(model);
+            }
+            return list;
+        }
+
+        /// <summary>
+        /// 实体列表转换成DataTable
+        /// </summary>
+        /// <typeparam name="T">实体</typeparam>
+        /// <param name="list"> 实体列表</param>
+        /// <returns>映射为数据表</returns>
+        public static DataTable ListToDataTable<T>(IList<T> list)
+            where T : class
+        {
+            if (list == null || list.Count <= 0)
+            {
+                return null;
+            }
+            DataTable dt = new DataTable(typeof(T).Name);
+            DataColumn column;
+            DataRow row;
+
+            PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
+
+            int length = myPropertyInfo.Length;
+            bool createColumn = true;
+
+            foreach (T t in list)
+            {
+                if (t == null)
+                {
+                    continue;
+                }
+
+                row = dt.NewRow();
+                for (int i = 0; i < length; i++)
+                {
+                    PropertyInfo pi = myPropertyInfo[i];
+                    string name = pi.Name;
+                    if (createColumn)
+                    {
+                        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;
+        }
+
+        /// <summary>
+        /// 将泛型集合类转换成DataTable
+        /// </summary>
+        /// <typeparam name="T">集合项类型</typeparam>
+        /// <param name="list">集合</param>
+        /// <returns>数据集(表)</returns>
+        public static DataTable ToDataTable<T>(IList<T> list)
+        {
+            return ToDataTable<T>(list, null);
+        }
+
+        /// <summary>
+        /// 将泛型集合类转换成DataTable
+        /// </summary>
+        /// <typeparam name="T">集合项类型</typeparam>
+        /// <param name="list">集合</param>
+        /// <param name="propertyName">需要返回的列的列名</param>
+        /// <returns>数据集(表)</returns>
+        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
+        {
+            List<string> propertyNameList = new List<string>();
+            if (propertyName != null)
+                propertyNameList.AddRange(propertyName);
+
+            DataTable result = new DataTable();
+            if (list.Count > 0)
+            {
+                PropertyInfo[] propertys = list[0].GetType().GetProperties();
+                foreach (PropertyInfo pi in propertys)
+                {
+                    if (propertyNameList.Count == 0)
+                    {
+                        result.Columns.Add(pi.Name, pi.PropertyType);
+                    }
+                    else
+                    {
+                        if (propertyNameList.Contains(pi.Name))
+                        {
+                            result.Columns.Add(pi.Name, pi.PropertyType);
+                        }
+                    }
+                }
+
+                for (int i = 0; i < list.Count; i++)
+                {
+                    ArrayList tempList = new ArrayList();
+                    foreach (PropertyInfo pi in propertys)
+                    {
+                        if (propertyNameList.Count == 0)
+                        {
+                            object obj = pi.GetValue(list[i], null);
+                            tempList.Add(obj);
+                        }
+                        else
+                        {
+                            if (propertyNameList.Contains(pi.Name))
+                            {
+                                object obj = pi.GetValue(list[i], null);
+                                tempList.Add(obj);
+                            }
+                        }
+                    }
+                    object[] array = tempList.ToArray();
+                    result.LoadDataRow(array, true);
+                }
+            }
+            return result;
+        }
+
+        /// <summary>
+        /// 根据nameList里面的字段创建一个表格,返回该表格的DataTable
+        /// </summary>
+        /// <param name="nameList">包含字段信息的列表</param>
+        /// <returns>DataTable</returns>
+        public static DataTable CreateTable(List<string> nameList)
+        {
+            if (nameList.Count <= 0)
+                return null;
+
+            DataTable myDataTable = new DataTable();
+            foreach (string columnName in nameList)
+            {
+                myDataTable.Columns.Add(columnName, typeof(string));
+            }
+            return myDataTable;
+        }
+
+        /// <summary>
+        /// 通过字符列表创建表字段,字段格式可以是:
+        /// 1) a,b,c,d,e
+        /// 2) a|int,b|string,c|bool,d|decimal
+        /// </summary>
+        /// <param name="nameString">字符列表</param>
+        /// <returns>内存表</returns>
+        public static DataTable CreateTable(string nameString)
+        {
+            string[] nameArray = nameString.Split(new char[] { ',', ';' });
+            List<string> nameList = new List<string>();
+            DataTable dt = new DataTable();
+            foreach (string item in nameArray)
+            {
+                if (!string.IsNullOrEmpty(item))
+                {
+                    string[] subItems = item.Split('|');
+                    if (subItems.Length == 2)
+                    {
+                        dt.Columns.Add(subItems[0], ConvertType(subItems[1]));
+                    }
+                    else
+                    {
+                        dt.Columns.Add(subItems[0]);
+                    }
+                }
+            }
+            return dt;
+        }
+
+        /// <summary>
+        /// 根据类型名返回一个Type类型
+        /// </summary>
+        /// <param name="typeName">类型的名称</param>
+        /// <returns>Type对象</returns>
+        private static Type ConvertType(string typeName)
+        {
+            typeName = typeName.ToLower().Replace("system.", "");
+            Type newType = typeof(string);
+            switch (typeName)
+            {
+                case "boolean":
+                case "bool":
+                    newType = typeof(bool);
+                    break;
+                case "int16":
+                case "short":
+                    newType = typeof(short);
+                    break;
+                case "int32":
+                case "int":
+                    newType = typeof(int);
+                    break;
+                case "long":
+                case "int64":
+                    newType = typeof(long);
+                    break;
+                case "uint16":
+                case "ushort":
+                    newType = typeof(ushort);
+                    break;
+                case "uint32":
+                case "uint":
+                    newType = typeof(uint);
+                    break;
+                case "uint64":
+                case "ulong":
+                    newType = typeof(ulong);
+                    break;
+                case "single":
+                case "float":
+                    newType = typeof(float);
+                    break;
+
+                case "string":
+                    newType = typeof(string);
+                    break;
+                case "guid":
+                    newType = typeof(Guid);
+                    break;
+                case "decimal":
+                    newType = typeof(decimal);
+                    break;
+                case "double":
+                    newType = typeof(double);
+                    break;
+                case "datetime":
+                    newType = typeof(DateTime);
+                    break;
+                case "byte":
+                    newType = typeof(byte);
+                    break;
+                case "char":
+                    newType = typeof(char);
+                    break;
+            }
+            return newType;
+        }
+
+        /// <summary>
+        /// 获得从DataRowCollection转换成的DataRow数组
+        /// </summary>
+        /// <param name="drc">DataRowCollection</param>
+        /// <returns>DataRow数组</returns>
+        public static DataRow[] GetDataRowArray(DataRowCollection drc)
+        {
+            int count = drc.Count;
+            DataRow[] drs = new DataRow[count];
+            for (int i = 0; i < count; i++)
+            {
+                drs[i] = drc[i];
+            }
+            return drs;
+        }
+
+        /// <summary>
+        /// 将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构,
+        /// 否则当有元素长度大于第一个元素时,抛出异常
+        /// </summary>
+        /// <param name="rows">行数组</param>
+        /// <returns>将内存行组装成内存表</returns>
+        public static DataTable GetTableFromRows(DataRow[] rows)
+        {
+            if (rows.Length <= 0)
+            {
+                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;
+        }
+
+        /// <summary>
+        /// 排序表的视图
+        /// </summary>
+        /// <param name="dt">原内存表</param>
+        /// <param name="sorts">排序方式</param>
+        /// <returns>排序后的内存表</returns>
+        public static DataTable SortedTable(this DataTable dt, params string[] sorts)
+        {
+            if (dt.Rows.Count > 0)
+            {
+                string tmp = "";
+                for (int i = 0; i < sorts.Length; i++)
+                {
+                    tmp += sorts[i] + ",";
+                }
+                dt.DefaultView.Sort = tmp.TrimEnd(',');
+            }
+            return dt;
+        }
+
+        /// <summary>
+        /// 根据条件过滤表的内容
+        /// </summary>
+        /// <param name="dt">原内存表</param>
+        /// <param name="condition">过滤条件</param>
+        /// <returns>过滤后的内存表</returns>
+        public static DataTable FilterDataTable(this DataTable dt, string condition)
+        {
+            if (condition.Trim()?.Length == 0)
+            {
+                return dt;
+            }
+            else
+            {
+                DataTable newdt = new DataTable();
+                newdt = dt.Clone();
+                DataRow[] dr = dt.Select(condition);
+                for (int i = 0; i < dr.Length; i++)
+                {
+                    newdt.ImportRow((DataRow)dr[i]);
+                }
+                return newdt;
+            }
+        }
+    }
+}

+ 417 - 0
Masuit.Tools/DateTimeExt/CCalendarData.xml

@@ -0,0 +1,417 @@
+<?xml version="1.0" encoding="gb2312" ?>
+<HELLO>
+
+  <!-- 公历节日开始 -->
+  <AD>
+    <feast day="0101" name="元旦" sayhello="yes">
+      <hello>新年好!祝您在新的一年里身体健康,事业进步!</hello>
+      <!-- 从网站根目录算起 -->
+      <img>./img/theme/0101.gif</img>
+    </feast>
+    <feast day="0202" name="世界湿地日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0210" name="国际气象节" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0214" name="情人节" sayhello="yes">
+      <hello>祝天下有情人终成眷属!</hello>
+      <img></img>
+    </feast>
+    <feast day="0301" name="世界图书日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0303" name="全国爱耳日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0305" name="学雷锋纪念日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0308" name="妇女节" sayhello="yes">
+      <hello>妇女能顶半边天,谁说女子不如男!</hello>
+      <img></img>
+    </feast>
+    <feast day="0312" name="植树节" sayhello="yes">
+      <hello>植树造林,功德无量。</hello>
+      <img>./img/theme/0312.gif</img>
+    </feast>
+    <feast day="0314" name="国际警察日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0315" name="消费者权益日" sayhello="no">
+      <img>./img/theme/temp.gif</img>
+      <hello></hello>
+    </feast>
+    <feast day="0316" name="手拉手情系贫困地区全国行动日" sayhello="no">
+      <img>./img/theme/temp.gif</img>
+      <hello></hello>
+    </feast>
+    <feast day="0317" name="国际航海日" sayhello="no">
+      <img>./img/theme/temp.gif</img>
+      <hello></hello>
+    </feast>
+    <feast day="0318" name="全国科技人才活动日" sayhello="no">
+      <img>./img/theme/temp.gif</img>
+      <hello></hello>
+    </feast>
+    <feast day="0321" name="世界睡眠日 世界森林日 世界儿歌日 消除种族歧视国际日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0322" name="世界水日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0323" name="世界气象日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0324" name="世界防治结核病日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0401" name="愚人节" sayhello="no">
+      <img>./img/theme/temp.gif</img>
+      <hello></hello>
+    </feast>
+    <feast day="0407" name="世界卫生日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0422" name="世界地球日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0425" name="国际秘书节" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0501" name="劳动节" sayhello="yes">
+      <hello>今天是劳动节,怎么,您还在劳动吗?</hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0504" name="青年节" sayhello="yes">
+      <hello>美哉,我少年中国,与天不老!壮哉,我中国少年,与国无疆!</hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0505" name="全国碘缺乏病日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0508" name="世界红十字日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0512" name="护士节" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0515" name="国际家庭日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0517" name="世界电信日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0518" name="国际博物馆日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0519" name="全国助残日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0520" name="全国学生营养日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0522" name="国际生物多样性日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0523" name="国际牛奶日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0531" name="世界无烟日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0601" name="儿童节" sayhello="yes">
+      <hello>祝您儿童节快乐!</hello>
+      <img>./img/theme/0601.gif</img>
+    </feast>
+    <feast day="0605" name="世界环境日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0606" name="全国爱眼日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0617" name="防治荒漠化和干旱日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0623" name="国际奥林匹克日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0625" name="全国土地日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0626" name="国际禁毒日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0701" name="建党节 香港回归纪念" sayhello="yes">
+      <hello>庆祝中国共产党成立_YEARS_周年!</hello>
+      <startyear>1921</startyear>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0707" name="七七卢沟桥事变" sayhello="yes">
+      <hello>1937年7月7日,卢沟桥事变,全面抗战开始。</hello>
+      <startyear>1937</startyear>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0711" name="世界人口日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0801" name="建军节" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0908" name="国际扫盲日 国际新闻工作者团体日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0909" name="毛泽东逝世纪念" sayhello="yes">
+      <hello>伟大领袖毛泽东主席逝世_YEARS_周年。</hello>
+      <startyear>1976</startyear>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0910" name="中国教师节" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0916" name="国际臭氧层保护日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0918" name="九一八事变" sayhello="yes">
+      <img></img>
+      <hello>1931年9月18日,日本帝国主义对我国沈阳北大营的中国驻军发动武装进攻,接着对我国东北地区进行大规模武装侵略。</hello>
+    </feast>
+    <feast day="0920" name="全国爱牙日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0921" name="国际和平日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0927" name="世界旅游日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="0928" name="国际聋人日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="1001" name="国庆节" sayhello="yes">
+      <hello>热烈庆祝中华人民共和国成立_YEARS_周年!</hello>
+      <startyear>1949</startyear>
+      <img>./img/theme/1001.gif</img>
+    </feast>
+    <feast day="1001" name="老人节" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="1001" name="国际音乐日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1004" name="世界动物日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1008" name="全国高血压日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1009" name="世界邮政日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="1010" name="世界精神卫生日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1014" name="世界标准日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="1015" name="国际盲人节" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1016" name="世界粮食日" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="1017" name="世界消除贫困日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1022" name="世界传统医药日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1024" name="联合国日" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="1031" name="万圣节" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="1108" name="中国记者日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1109" name="消防宣传日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1112" name="孙中山诞辰纪念" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="1114" name="世界糖尿病日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1117" name="国际大学生节" sayhello="no">
+      <img></img>
+      <hello></hello>
+    </feast>
+    <feast day="1201" name="世界艾滋病日" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="1203" name="世界残疾人日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1209" name="世界足球日" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1213" name="南京大屠杀纪念日" sayhello="yes">
+      <hello>南京大屠杀_YEARS_周年。1937年12月13日,日军占领南京,进行长达6周的血腥大屠杀,杀害我军民30余万人。</hello>
+      <startyear>1937</startyear>
+      <img></img>
+    </feast>
+    <feast day="1220" name="澳门回归纪念" sayhello="no">
+      <hello></hello>
+      <img></img>
+    </feast>
+    <feast day="1224" name="圣诞节平安夜" sayhello="yes">
+      <hello>We wish you a merry christmas。</hello>
+      <img>./img/theme/1225.gif</img>
+    </feast>
+    <feast day="1225" name="圣诞节" sayhello="yes">
+      <hello>圣诞快乐。</hello>
+      <img>./img/theme/1225.gif</img>
+    </feast>
+  </AD>
+  <!-- 公历节日结束 -->
+
+  <!-- 农历节日开始 -->
+  <LUNAR>
+    <feast day="0101" name="春节" sayhello="yes">
+      <hello>恭喜发财!新年进步!万事如意!</hello>
+      <img>./img/theme/spring.gif</img>
+    </feast>
+    <feast day="0115" name="元宵节" sayhello="yes">
+      <hello>年年元夜时,花市灯如昼。月上柳梢头,人约黄昏后。</hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0505" name="端午节" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0707" name="七夕情人节" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0715" name="中元节" sayhello="no">
+      <hello></hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0815" name="中秋节" sayhello="yes">
+      <hello>海上升明月 天涯共此时</hello>
+      <img>./img/theme/c815.gif</img>
+    </feast>
+    <feast day="0909" name="重阳节" sayhello="yes">
+      <hello>人生易老天难老,岁岁重阳。今又重阳,战地黄花分外香。</hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="1208" name="腊八节" sayhello="yes">
+      <hello>谁愿意跟我去侠客岛喝腊八粥?</hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+    <feast day="0100" name="除夕" sayhello="yes">
+      <hello>炮竹声中一岁除,春风送暖入屠苏。千家万户瞳瞳日,总把新桃换旧符。</hello>
+      <img>./img/theme/temp.gif</img>
+    </feast>
+  </LUNAR>
+  <!-- 农历节日结束 -->
+
+  <!-- 普通日子开始 -->
+  <NORMAL>
+    <day time1="2301" time2="2359" sayhello="yes">
+      <hello>深夜了!您应该休息了。</hello>
+      <img>./img/theme/latenight.gif</img>
+    </day>
+    <day time1="1901" time2="2300" sayhello="yes">
+      <hello>晚上好!还在工作吗?</hello>
+      <img>./img/theme/night.gif</img>
+    </day>
+    <day time1="1801" time2="1900" sayhello="yes">
+      <hello>傍晚好!是时候吃晚饭了。</hello>
+      <img>./img/theme/dusk.gif</img>
+    </day>
+    <day time1="1301" time2="1800" sayhello="yes">
+      <hello>下午好!要振作精神哦!</hello>
+      <img>./img/theme/afternoon.gif</img>
+    </day>
+    <day time1="1201" time2="1300" sayhello="yes">
+      <hello>中午好!吃过午饭了吗?</hello>
+      <img>./img/theme/midday.gif</img>
+    </day>
+    <day time1="0901" time2="1200" sayhello="yes">
+      <hello>上午好!努力工作哦!</hello>
+      <img>./img/theme/ackemma.gif</img>
+    </day>
+    <day time1="0601" time2="0900" sayhello="yes">
+      <hello>早上好!休息得好吗?</hello>
+      <img>./img/theme/morning.gif</img>
+    </day>
+    <day time1="0000" time2="0600" sayhello="yes">
+      <hello>深夜了!您应该休息了。</hello>
+      <img>./img/theme/latenight.gif</img>
+    </day>
+  </NORMAL>
+  <!-- 普通日子结束 -->
+
+</HELLO>

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

@@ -0,0 +1,980 @@
+using System;
+using System.IO;
+using System.Reflection;
+using System.Xml;
+
+namespace Masuit.Tools.DateTimeExt
+{
+    /// <summary>
+    /// 日历操作
+    /// </summary>
+    public 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 string.Format("{0:00}{1:00}", m, d);
+        }
+
+        /// <summary>
+        /// 从嵌入资源中读取文件内容(e.g: xml).
+        /// </summary>
+        /// <param name="fileWholeName">嵌入资源文件名,包括项目的命名空间.</param>
+        /// <returns>资源中的文件内容.</returns>
+        public static string ReadFileFromEmbedded(string fileWholeName)
+        {
+            //文件属性-生成操作-嵌入的资源
+            string result = string.Empty;
+
+            using (TextReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(fileWholeName)))
+            {
+                result = reader.ReadToEnd();
+            }
+            return result;
+        }
+
+        #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 string AnimalsYear(int y)
+        {
+            return animals[(y - 4) % 12];
+        }
+
+        /// <summary>
+        ///传入月日的offset 传回天干地支, 0=甲子
+        /// </summary>
+        /// <param name="num">月日的偏差</param>
+        private string Cyclical(int num)
+        {
+            return gan[num % 10] + zhi[num % 12];
+        }
+
+        /// <summary>
+        /// 传入offset 传回干支, 0=甲子
+        /// </summary>
+        /// <param name="y">公元年</param>
+        private 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 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 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 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 StructDateFullInfo GetDateTidyInfo(DateTime d)
+        {
+            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;
+            }
+
+            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 StructDateFullInfo GetDateInfo(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 StructDateFullInfo getChinaDate(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
+    }
+}

+ 178 - 0
Masuit.Tools/DateTimeExt/ChineseCalendar.cs

@@ -0,0 +1,178 @@
+using System;
+using System.Globalization;
+
+namespace Masuit.Tools.DateTimeExt
+{
+    /// <summary>
+    /// 中国农历年处理类用net自带类
+    /// </summary>
+    public static class ChineseCalendar
+    {
+        /// <summary>
+        /// 实例化一个  ChineseLunisolarCalendar
+        /// </summary>
+        private static ChineseLunisolarCalendar cCalendar = new ChineseLunisolarCalendar();
+
+        /// <summary>
+        /// 获取农历当前日期
+        /// </summary>
+        /// <returns>当前农历日期</returns>
+        public static string GetChineseDateTimeNow()
+        {
+            return GetChineseDateTime(DateTime.Now);
+        }
+
+        /// <summary>
+        /// 根据公历获取农历日期
+        /// </summary>
+        /// <param name="datetime">公历日期</param>
+        /// <returns>公历日期的字符串形式</returns>
+        public static string GetChineseDateTime(this DateTime datetime)
+        {
+            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)
+            {
+                if (leapMonth == lmonth)
+                {
+                    //闰月
+                    isleap = true;
+                    lmonth--;
+                }
+                else if (lmonth > leapMonth)
+                {
+                    lmonth--;
+                }
+            }
+            return string.Concat(GetLunisolarYear(lyear), "年", isleap ? "闰" : string.Empty, GetLunisolarMonth(lmonth), "月", GetLunisolarDay(lday));
+        }
+
+        /// <summary>
+        /// 返回农历日期
+        /// </summary>
+        public static string Now => GetChineseDateTimeNow();
+
+        /// <summary>
+        /// 最大支持日期
+        /// </summary>
+        public static DateTime MaxSupportedDateTime => cCalendar.MaxSupportedDateTime;
+
+        /// <summary>
+        /// 最小支持日期
+        /// </summary>
+        public static DateTime MinSupportedDateTime { get; } = cCalendar.MinSupportedDateTime;
+
+        /// <summary>
+        /// 返回生肖
+        /// </summary>
+        /// <param name="datetime">公历日期</param>
+        /// <returns>生肖</returns>
+        public static string GetShengXiao(DateTime datetime)
+        {
+            return shengxiao[cCalendar.GetTerrestrialBranch(cCalendar.GetSexagenaryYear(datetime)) - 1];
+        }
+
+        #region 农历年
+
+        /// <summary>
+        /// 十天干
+        /// </summary>
+        private static string[] tiangan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
+
+        /// <summary>
+        /// 十二地支
+        /// </summary>
+        private static string[] dizhi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
+
+        /// <summary>
+        /// 十二生肖
+        /// </summary>
+        private static string[] shengxiao = { "鼠", "牛", "虎", "免", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
+
+        /// <summary>
+        /// 返回农历天干地支年
+        /// </summary>
+        /// <param name="year">农历年</param>
+        /// <exception cref="ArgumentOutOfRangeException"></exception>
+        /// <returns>天干地支年</returns>
+        public static string GetLunisolarYear(int year)
+        {
+            if (year > 3)
+            {
+                int tgIndex = (year - 4) % 10;
+                int dzIndex = (year - 4) % 12;
+
+                return string.Concat(tiangan[tgIndex], dizhi[dzIndex], "[", shengxiao[dzIndex], "]");
+            }
+
+            throw new ArgumentOutOfRangeException("无效的年份!");
+        }
+
+        #endregion
+
+        #region 农历月
+
+        /// <summary>
+        /// 农历月
+        /// </summary>
+        private static string[] months = { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二(腊)" };
+
+        /// <summary>
+        /// 返回农历月
+        /// </summary>
+        /// <param name="month">月份</param>
+        /// <exception cref="ArgumentOutOfRangeException"></exception>
+        /// <returns>农历月</returns>
+        public static string GetLunisolarMonth(int month)
+        {
+            if (month < 13 && month > 0)
+            {
+                return months[month - 1];
+            }
+
+            throw new ArgumentOutOfRangeException("无效的月份!");
+        }
+
+        #endregion
+
+        #region 农历日
+        private static string[] days1 = { "初", "十", "廿", "三" };
+
+        /// <summary>
+        /// 日
+        /// </summary>
+        private static string[] days = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
+
+        /// <summary>
+        /// 返回农历日
+        /// </summary>
+        /// <param name="day">阳历日</param>
+        /// <exception cref="ArgumentOutOfRangeException"></exception>
+        /// <returns>农历日</returns>
+        public static string GetLunisolarDay(int day)
+        {
+            if (day > 0 && day < 32)
+            {
+                if (day != 20 && day != 30)
+                {
+                    return string.Concat(days1[(day - 1) / 10], days[(day - 1) % 10]);
+                }
+                else
+                {
+                    return string.Concat(days[(day - 1) / 10], days1[1]);
+                }
+            }
+
+            throw new ArgumentOutOfRangeException("无效的日!");
+        }
+
+        #endregion
+    }
+}

+ 152 - 0
Masuit.Tools/DateTimeExt/DateTimeHelper.cs

@@ -0,0 +1,152 @@
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text.RegularExpressions;
+
+namespace Masuit.Tools.DateTimeExt
+{
+    /// <summary>
+    /// 日期时间帮助类
+    /// </summary>
+    public static class DateTimeHelper
+    {
+        private static System.DateTime dt = System.DateTime.Now;
+
+        /// <summary>
+        /// 获取某一年有多少周
+        /// </summary>
+        /// <param name="year">年份</param>
+        /// <returns>该年周数</returns>
+        public static int GetWeekAmount(int year)
+        {
+            var end = new System.DateTime(year, 12, 31); //该年最后一天
+            var gc = new GregorianCalendar();
+            return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday); //该年星期数
+        }
+
+        /// <summary>
+        /// 返回年度第几个星期   默认星期日是第一天
+        /// </summary>
+        /// <param name="date">时间</param>
+        /// <returns>第几周</returns>
+        public static int WeekOfYear(System.DateTime date)
+        {
+            System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
+            return gc.GetWeekOfYear(date, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
+        }
+
+        /// <summary>
+        /// 返回年度第几个星期
+        /// </summary>
+        /// <param name="date">时间</param>
+        /// <param name="week">一周的开始日期</param>
+        /// <returns>第几周</returns>
+        public static int WeekOfYear(System.DateTime date, DayOfWeek week)
+        {
+            System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
+            return gc.GetWeekOfYear(date, System.Globalization.CalendarWeekRule.FirstDay, week);
+        }
+
+        /// <summary>
+        /// 得到一年中的某周的起始日和截止日
+        /// 年 nYear
+        /// 周数 nNumWeek
+        /// 周始 out dtWeekStart
+        /// 周终 out dtWeekeEnd
+        /// </summary>
+        /// <param name="nYear">年份</param>
+        /// <param name="nNumWeek">第几周</param>
+        /// <param name="dtWeekStart">开始日期</param>
+        /// <param name="dtWeekeEnd">结束日期</param>
+        public static void GetWeekTime(int nYear, int nNumWeek, out System.DateTime dtWeekStart, out System.DateTime dtWeekeEnd)
+        {
+            System.DateTime dt = new System.DateTime(nYear, 1, 1);
+            dt += new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
+            dtWeekStart = dt.AddDays(-(int)dt.DayOfWeek + (int)DayOfWeek.Monday);
+            dtWeekeEnd = dt.AddDays((int)DayOfWeek.Saturday - (int)dt.DayOfWeek + 1);
+        }
+
+        /// <summary>
+        /// 得到一年中的某周的起始日和截止日    周一到周五  工作日
+        /// </summary>
+        /// <param name="nYear">年份</param>
+        /// <param name="nNumWeek">第几周</param>
+        /// <param name="dtWeekStart">开始日期</param>
+        /// <param name="dtWeekeEnd">结束日期</param>
+        public static void GetWeekWorkTime(int nYear, int nNumWeek, out System.DateTime dtWeekStart, out System.DateTime dtWeekeEnd)
+        {
+            System.DateTime dt = new System.DateTime(nYear, 1, 1);
+            dt += new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
+            dtWeekStart = dt.AddDays(-(int)dt.DayOfWeek + (int)DayOfWeek.Monday);
+            dtWeekeEnd = dt.AddDays((int)DayOfWeek.Saturday - (int)dt.DayOfWeek + 1).AddDays(-2);
+        }
+
+        #region P/Invoke 设置本地时间
+
+        [DllImport("kernel32.dll")]
+        private static extern bool SetLocalTime(ref SYSTEMTIME time);
+
+        [StructLayout(LayoutKind.Sequential)]
+        private struct SYSTEMTIME
+        {
+            public short year;
+            public short month;
+            public short dayOfWeek;
+            public short day;
+            public short hour;
+            public short minute;
+            public short second;
+            public short milliseconds;
+        }
+
+        /// <summary>
+        /// 设置本地计算机时间
+        /// </summary>
+        /// <param name="dt">DateTime对象</param>
+        public static void SetLocalTime(System.DateTime dt)
+        {
+            SYSTEMTIME st;
+
+            st.year = (short)dt.Year;
+            st.month = (short)dt.Month;
+            st.dayOfWeek = (short)dt.DayOfWeek;
+            st.day = (short)dt.Day;
+            st.hour = (short)dt.Hour;
+            st.minute = (short)dt.Minute;
+            st.second = (short)dt.Second;
+            st.milliseconds = (short)dt.Millisecond;
+
+            SetLocalTime(ref st);
+        }
+
+        #endregion
+
+        #region 获取网络时间
+
+        /// <summary>
+        /// 从指定的字符串中获取整数
+        /// </summary>
+        /// <param name="origin">原始的字符串</param>
+        /// <param name="fullMatch">是否完全匹配,若为false,则返回字符串中的第一个整数数字</param>
+        /// <returns>整数数字</returns>
+        private static int GetInt(string origin, bool fullMatch)
+        {
+            if (string.IsNullOrEmpty(origin))
+            {
+                return 0;
+            }
+            origin = origin.Trim();
+            if (!fullMatch)
+            {
+                string pat = @"-?\d+";
+                Regex reg = new Regex(pat);
+                origin = reg.Match(origin.Trim()).Value;
+            }
+            int res = 0;
+            int.TryParse(origin, out res);
+            return res;
+        }
+        #endregion
+
+    }
+}

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

@@ -0,0 +1,406 @@
+
+using System;
+
+namespace Masuit.Tools.DateTimeExt
+{
+    /// <summary>
+    /// 日期操作工具类
+    /// </summary>
+    public static class DateUtil
+    {
+        /// <summary>
+        /// 返回相对于当前时间的相对天数
+        /// </summary>
+        /// <param name="relativeday">相对天数</param>
+        public static string GetDateTime(int relativeday)
+        {
+            return System.DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
+        }
+
+        /// <summary>
+        /// 返回标准时间格式string
+        /// </summary>
+        public static string GetDateTimeF()
+        {
+            return System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
+        }
+
+        /// <summary>
+        /// 返回标准时间 
+        /// </summary>
+        /// <param name="fDateTime">日期时间字符串</param>
+        /// <param name="formatStr">格式</param>
+        public static string GetStandardDateTime(string fDateTime, string formatStr)
+        {
+            if (fDateTime == "0000-0-0 0:00:00")
+            {
+                return fDateTime;
+            }
+            System.DateTime s = Convert.ToDateTime(fDateTime);
+            return s.ToString(formatStr);
+        }
+
+        /// <summary>
+        /// 返回标准时间 yyyy-MM-dd HH:mm:ss
+        /// </summary>
+        /// <param name="fDateTime">日期时间字符串</param>
+        public static string GetStandardDateTime(string fDateTime)
+        {
+            return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
+        }
+
+        /// <summary>
+        /// 返回本年有多少天
+        /// </summary>
+        /// <param name="iYear">年份</param>
+        /// <returns>本年的天数</returns>
+        public static int GetDaysOfYear(int iYear)
+        {
+            int cnt = 0;
+            if (IsRuYear(iYear))
+            {
+                //闰年多 1 天 即:2 月为 29 天
+                cnt = 366;
+            }
+            else
+            {
+                //--非闰年少1天 即:2 月为 28 天
+                cnt = 365;
+            }
+            return cnt;
+        }
+
+        /// <summary>本年有多少天</summary>
+        /// <param name="dt">日期</param>
+        /// <returns>本天在当年的天数</returns>
+        public static int GetDaysOfYear(System.DateTime dt)
+        {
+            //取得传入参数的年份部分,用来判断是否是闰年
+            int n = dt.Year;
+            if (IsRuYear(n))
+            {
+                //闰年多 1 天 即:2 月为 29 天
+                return 366;
+            }
+            else
+            {
+                //--非闰年少1天 即:2 月为 28 天
+                return 365;
+            }
+        }
+
+        /// <summary>本月有多少天</summary>
+        /// <param name="iYear">年</param>
+        /// <param name="Month">月</param>
+        /// <returns>天数</returns>
+        public static int GetDaysOfMonth(int iYear, int Month)
+        {
+            int days = 0;
+            switch (Month)
+            {
+                case 1:
+                    days = 31;
+                    break;
+                case 2:
+                    if (IsRuYear(iYear))
+                    {
+                        //闰年多 1 天 即:2 月为 29 天
+                        days = 29;
+                    }
+                    else
+                    {
+                        //--非闰年少1天 即:2 月为 28 天
+                        days = 28;
+                    }
+
+                    break;
+                case 3:
+                    days = 31;
+                    break;
+                case 4:
+                    days = 30;
+                    break;
+                case 5:
+                    days = 31;
+                    break;
+                case 6:
+                    days = 30;
+                    break;
+                case 7:
+                    days = 31;
+                    break;
+                case 8:
+                    days = 31;
+                    break;
+                case 9:
+                    days = 30;
+                    break;
+                case 10:
+                    days = 31;
+                    break;
+                case 11:
+                    days = 30;
+                    break;
+                case 12:
+                    days = 31;
+                    break;
+            }
+            return days;
+        }
+
+        /// <summary>本月有多少天</summary>
+        /// <param name="dt">日期</param>
+        /// <returns>天数</returns>
+        public static int GetDaysOfMonth(System.DateTime dt)
+        {
+            //--------------------------------//
+            //--从dt中取得当前的年,月信息  --//
+            //--------------------------------//
+            int month, days = 0;
+            var year = dt.Year;
+            month = dt.Month;
+
+            //--利用年月信息,得到当前月的天数信息。
+            switch (month)
+            {
+                case 1:
+                    days = 31;
+                    break;
+                case 2:
+                    if (IsRuYear(year))
+                    {
+                        //闰年多 1 天 即:2 月为 29 天
+                        days = 29;
+                    }
+                    else
+                    {
+                        //--非闰年少1天 即:2 月为 28 天
+                        days = 28;
+                    }
+
+                    break;
+                case 3:
+                    days = 31;
+                    break;
+                case 4:
+                    days = 30;
+                    break;
+                case 5:
+                    days = 31;
+                    break;
+                case 6:
+                    days = 30;
+                    break;
+                case 7:
+                    days = 31;
+                    break;
+                case 8:
+                    days = 31;
+                    break;
+                case 9:
+                    days = 30;
+                    break;
+                case 10:
+                    days = 31;
+                    break;
+                case 11:
+                    days = 30;
+                    break;
+                case 12:
+                    days = 31;
+                    break;
+            }
+
+            return days;
+        }
+
+        /// <summary>返回当前日期的星期名称</summary>
+        /// <param name="idt">日期</param>
+        /// <returns>星期名称</returns>
+        public static string GetWeekNameOfDay(System.DateTime idt)
+        {
+            string week = "";
+
+            var dt = idt.DayOfWeek.ToString();
+            switch (dt)
+            {
+                case "Mondy":
+                    week = "星期一";
+                    break;
+                case "Tuesday":
+                    week = "星期二";
+                    break;
+                case "Wednesday":
+                    week = "星期三";
+                    break;
+                case "Thursday":
+                    week = "星期四";
+                    break;
+                case "Friday":
+                    week = "星期五";
+                    break;
+                case "Saturday":
+                    week = "星期六";
+                    break;
+                case "Sunday":
+                    week = "星期日";
+                    break;
+            }
+            return week;
+        }
+
+        /// <summary>返回当前日期的星期编号</summary>
+        /// <param name="idt">日期</param>
+        /// <returns>星期数字编号</returns>
+        public static string GetWeekNumberOfDay(System.DateTime idt)
+        {
+            string week = "";
+
+            var dt = idt.DayOfWeek.ToString();
+            switch (dt)
+            {
+                case "Mondy":
+                    week = "1";
+                    break;
+                case "Tuesday":
+                    week = "2";
+                    break;
+                case "Wednesday":
+                    week = "3";
+                    break;
+                case "Thursday":
+                    week = "4";
+                    break;
+                case "Friday":
+                    week = "5";
+                    break;
+                case "Saturday":
+                    week = "6";
+                    break;
+                case "Sunday":
+                    week = "7";
+                    break;
+            }
+            return week;
+        }
+
+        /// <summary>判断当前日期所属的年份是否是闰年,私有函数</summary>
+        /// <param name="idt">日期</param>
+        /// <returns>是闰年:True ,不是闰年:False</returns>
+        private static bool IsRuYear(System.DateTime idt)
+        {
+            //形式参数为日期类型 
+            //例如:2003-12-12
+            var n = idt.Year;
+
+            if ((n % 400 == 0) || (n % 4 == 0 && n % 100 != 0))
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        /// <summary>判断当前年份是否是闰年,私有函数</summary>
+        /// <param name="iYear">年份</param>
+        /// <returns>是闰年:True ,不是闰年:False</returns>
+        private static bool IsRuYear(int iYear)
+        {
+            //形式参数为年份
+            //例如:2003
+            var n = iYear;
+
+            if ((n % 400 == 0) || (n % 4 == 0 && n % 100 != 0))
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// 将输入的字符串转化为日期。如果字符串的格式非法,则返回当前日期。
+        /// </summary>
+        /// <param name="strInput">输入字符串</param>
+        /// <returns>日期对象</returns>
+        public static System.DateTime ConvertStringToDate(string strInput)
+        {
+            System.DateTime oDateTime;
+
+            try
+            {
+                oDateTime = System.DateTime.Parse(strInput);
+            }
+            catch (Exception)
+            {
+                oDateTime = System.DateTime.Today;
+            }
+
+            return oDateTime;
+        }
+
+        /// <summary>
+        /// 将日期对象转化为格式字符串
+        /// </summary>
+        /// <param name="oDateTime">日期对象</param>
+        /// <param name="strFormat">
+        /// 格式:
+        ///		"SHORTDATE"===短日期
+        ///		"LONGDATE"==长日期
+        ///		其它====自定义格式
+        /// </param>
+        /// <returns>日期字符串</returns>
+        public static string ConvertDateToString(System.DateTime oDateTime, string strFormat)
+        {
+            string strDate = "";
+
+            try
+            {
+                switch (strFormat.ToUpper())
+                {
+                    case "SHORTDATE":
+                        strDate = oDateTime.ToShortDateString();
+                        break;
+                    case "LONGDATE":
+                        strDate = oDateTime.ToLongDateString();
+                        break;
+                    default:
+                        strDate = oDateTime.ToString(strFormat);
+                        break;
+                }
+            }
+            catch (Exception)
+            {
+                strDate = oDateTime.ToShortDateString();
+            }
+
+            return strDate;
+        }
+
+        /// <summary>
+        /// 判断是否为合法日期,必须大于1800年1月1日
+        /// </summary>
+        /// <param name="strDate">输入日期字符串</param>
+        /// <returns>True/False</returns>
+        public static bool IsDateTime(string strDate)
+        {
+            try
+            {
+                System.DateTime oDate = System.DateTime.Parse(strDate);
+                if (oDate.CompareTo(System.DateTime.Parse("1800-1-1")) > 0)
+                    return true;
+                else
+                    return false;
+            }
+            catch (Exception)
+            {
+                return false;
+            }
+        }
+    }
+}
+

+ 475 - 0
Masuit.Tools/DateTimeExt/TimeHelper.cs

@@ -0,0 +1,475 @@
+using System;
+
+namespace Masuit.Tools.DateTimeExt
+{
+    /// <summary>
+    /// 时间相关操作帮助类
+    /// </summary>
+    public static class TimeHelper
+    {
+        #region 时间相关操作类
+
+        /// <summary>
+        /// 获得一段时间内有多少小时
+        /// </summary>
+        /// <param name="dtStar">起始时间</param>
+        /// <param name="dtEnd">终止时间</param>
+        /// <returns>小时差</returns>
+        public static string GetTimeDelay(this System.DateTime dtStar, System.DateTime dtEnd)
+        {
+            long lTicks = (dtEnd.Ticks - dtStar.Ticks) / 10000000;
+            string sTemp = (lTicks / 3600).ToString().PadLeft(2, '0') + ":";
+            sTemp += ((lTicks % 3600) / 60).ToString().PadLeft(2, '0') + ":";
+            sTemp += ((lTicks % 3600) % 60).ToString().PadLeft(2, '0');
+            return sTemp;
+        }
+        /// <summary>
+        /// 获得8位时间整型数字
+        /// </summary>
+        /// <param name="dt">当前的日期时间对象</param>
+        /// <returns>8位时间整型数字</returns>
+        public static string GetDateString(this System.DateTime dt)
+        {
+            return dt.Year.ToString() + dt.Month.ToString().PadLeft(2, '0') + dt.Day.ToString().PadLeft(2, '0');
+        }
+        #endregion
+
+        #region 返回每月的第一天和最后一天
+        /// <summary>
+        ///  返回每月的第一天和最后一天
+        /// </summary>
+        /// <param name="month">月份</param>
+        /// <param name="firstDay">第一天</param>
+        /// <param name="lastDay">最后一天</param>
+        public static void ReturnDateFormat(int month, out string firstDay, out string lastDay)
+        {
+            int year = DateTime.Now.Year + (month / 12);
+            if (month != 12)
+            {
+                month %= 12;
+            }
+            switch (month)
+            {
+                case 1:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-31");
+                    break;
+                case 2:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    if (System.DateTime.IsLeapYear(System.DateTime.Now.Year))
+                        lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-29");
+                    else
+                        lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-28");
+                    break;
+                case 3:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString("yyyy-0" + month + "-31");
+                    break;
+                case 4:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-30");
+                    break;
+                case 5:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-31");
+                    break;
+                case 6:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-30");
+                    break;
+                case 7:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-31");
+                    break;
+                case 8:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-31");
+                    break;
+                case 9:
+                    firstDay = System.DateTime.Now.ToString(year + "-0" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-0" + month + "-30");
+                    break;
+                case 10:
+                    firstDay = System.DateTime.Now.ToString(year + "-" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-" + month + "-31");
+                    break;
+                case 11:
+                    firstDay = System.DateTime.Now.ToString(year + "-" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-" + month + "-30");
+                    break;
+                default:
+                    firstDay = System.DateTime.Now.ToString(year + "-" + month + "-01");
+                    lastDay = System.DateTime.Now.ToString(year + "-" + month + "-31");
+                    break;
+            }
+        }
+        #endregion
+
+        #region  将时间格式化成 年月日 的形式,如果时间为null,返回当前系统时间
+
+        /// <summary>
+        /// 将时间格式化成 年月日 的形式,如果时间为null,返回当前系统时间
+        /// </summary>
+        /// <param name="dt">年月日分隔符</param>
+        /// <param name="Separator">分隔符</param>
+        /// <returns>xxxx年xx月xx日</returns>
+        public static string GetFormatDate(this System.DateTime dt, char Separator)
+        {
+            if (dt != null && !dt.Equals(DBNull.Value))
+            {
+                string tem = string.Format("yyyy{0}MM{1}dd", Separator, Separator);
+                return dt.ToString(tem);
+            }
+            else
+            {
+                return GetFormatDate(System.DateTime.Now, Separator);
+            }
+        }
+        #endregion
+
+        #region 将时间格式化成 时分秒 的形式,如果时间为null,返回当前系统时间
+        /// <summary>
+        /// 将时间格式化成 时分秒 的形式,如果时间为null,返回当前系统时间
+        /// </summary>
+        /// <param name="dt">当前日期时间对象</param>
+        /// <param name="Separator">分隔符</param>
+        /// <returns> xx时xx分xx秒 </returns>
+        public static string GetFormatTime(this System.DateTime dt, char Separator)
+        {
+            if (dt != null && !dt.Equals(DBNull.Value))
+            {
+                string tem = string.Format("hh{0}mm{1}ss", Separator, Separator);
+                return dt.ToString(tem);
+            }
+            else
+            {
+                return GetFormatDate(System.DateTime.Now, Separator);
+            }
+        }
+        #endregion
+
+        #region  把秒转换成分钟
+
+        /// <summary>
+        /// 把秒转换成分钟
+        /// </summary>
+        /// <param name="Second">秒数</param>
+        /// <returns>分钟数</returns>
+        public static int SecondToMinute(int Second)
+        {
+            decimal mm = (decimal)((decimal)Second / (decimal)60);
+            return Convert.ToInt32(Math.Ceiling(mm));
+        }
+        #endregion
+
+        #region 返回某年某月最后一天
+        /// <summary>
+        /// 返回某年某月最后一天
+        /// </summary>
+        /// <param name="year">年份</param>
+        /// <param name="month">月份</param>
+        /// <returns>日</returns>
+        public static int GetMonthLastDate(int year, int month)
+        {
+            System.DateTime lastDay = new System.DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
+            int Day = lastDay.Day;
+            return Day;
+        }
+        #endregion
+
+        #region 返回时间差
+        /// <summary>
+        /// 返回时间差
+        /// </summary>
+        /// <param name="DateTime1">时间1</param>
+        /// <param name="DateTime2">时间2</param>
+        /// <returns>时间差</returns>
+        public static string DateDiff(System.DateTime DateTime1, System.DateTime DateTime2)
+        {
+            string dateDiff = null;
+            try
+            {
+                TimeSpan ts = DateTime2 - DateTime1;
+                if (ts.Days >= 1)
+                {
+                    dateDiff = DateTime1.Month.ToString() + "月" + DateTime1.Day.ToString() + "日";
+                }
+                else
+                {
+                    if (ts.Hours > 1)
+                    {
+                        dateDiff = ts.Hours.ToString() + "小时前";
+                    }
+                    else
+                    {
+                        dateDiff = ts.Minutes.ToString() + "分钟前";
+                    }
+                }
+            }
+            catch
+            {
+            }
+            return dateDiff;
+        }
+        /// <summary>
+        /// 时间差
+        /// </summary>
+        /// <param name="beginTime">开始时间</param>
+        /// <param name="endTime">结束时间</param>
+        /// <returns>时间差</returns>
+        public static string GetDiffTime(System.DateTime beginTime, System.DateTime endTime)
+        {
+            int i = 0;
+            return GetDiffTime(beginTime, endTime, ref i);
+        }
+
+        /// <summary>
+        /// 计算2个时间差
+        /// </summary>
+        /// <param name="beginTime">开始时间</param>
+        /// <param name="endTime">结束时间</param>
+        /// <param name="mindTime">中间的时间</param>
+        /// <returns>时间差</returns>
+        public static string GetDiffTime(System.DateTime beginTime, System.DateTime endTime, ref int mindTime)
+        {
+            string strResout = string.Empty;
+            //获得2时间的时间间隔秒计算
+            //TimeSpan span = endTime - beginTime;
+            TimeSpan span = endTime.Subtract(beginTime);
+
+            int iTatol = Convert.ToInt32(span.TotalSeconds);
+            int iMinutes = 1 * 60;
+            int iHours = iMinutes * 60;
+            int iDay = iHours * 24;
+            int iMonth = iDay * 30;
+            int iYear = iMonth * 12;
+
+            //提醒时间,到了返回1,否则返回0
+            if (mindTime > iTatol && iTatol > 0)
+            {
+                mindTime = 1;
+            }
+            else
+            {
+                mindTime = 0;
+            }
+
+            if (iTatol > iYear)
+            {
+                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;
+        }
+
+        #endregion
+
+        #region 获得两个日期的间隔
+        /// <summary>
+        /// 获得两个日期的间隔
+        /// </summary>
+        /// <param name="DateTime1">日期一。</param>
+        /// <param name="DateTime2">日期二。</param>
+        /// <returns>日期间隔TimeSpan。</returns>
+        public static TimeSpan DateDiff2(System.DateTime DateTime1, System.DateTime DateTime2)
+        {
+            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
+            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
+            TimeSpan ts = ts1.Subtract(ts2).Duration();
+            return ts;
+        }
+        #endregion
+
+        #region 格式化日期时间
+        /// <summary>
+        /// 格式化日期时间
+        /// </summary>
+        /// <param name="dateTime1">日期时间</param>
+        /// <param name="dateMode">显示模式</param>
+        /// <returns>0-9种模式的日期</returns>
+        public static string FormatDate(System.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();
+            }
+        }
+        #endregion
+
+        #region 得到随机日期
+        /// <summary>
+        /// 得到随机日期
+        /// </summary>
+        /// <param name="time1">起始日期</param>
+        /// <param name="time2">结束日期</param>
+        /// <returns>间隔日期之间的 随机日期</returns>
+        public static System.DateTime GetRandomTime(System.DateTime time1, System.DateTime time2)
+        {
+            Random random = new Random();
+            System.DateTime minTime = new System.DateTime();
+            System.DateTime maxTime = new System.DateTime();
+
+            System.TimeSpan ts = new System.TimeSpan(time1.Ticks - time2.Ticks);
+
+            // 获取两个时间相隔的秒数
+            double dTotalSecontds = ts.TotalSeconds;
+            int iTotalSecontds = 0;
+
+            if (dTotalSecontds > System.Int32.MaxValue)
+            {
+                iTotalSecontds = System.Int32.MaxValue;
+            }
+            else if (dTotalSecontds < System.Int32.MinValue)
+            {
+                iTotalSecontds = System.Int32.MinValue;
+            }
+            else
+            {
+                iTotalSecontds = (int)dTotalSecontds;
+            }
+            if (iTotalSecontds > 0)
+            {
+                minTime = time2;
+                maxTime = time1;
+            }
+            else if (iTotalSecontds < 0)
+            {
+                minTime = time1;
+                maxTime = time2;
+            }
+            else
+            {
+                return time1;
+            }
+
+            int maxValue = iTotalSecontds;
+
+            if (iTotalSecontds <= System.Int32.MinValue)
+                maxValue = System.Int32.MinValue + 1;
+
+            int i = random.Next(System.Math.Abs(maxValue));
+
+            return minTime.AddSeconds(i);
+        }
+        #endregion
+
+        #region 时间其他转换静态方法
+        /// <summary>
+        /// C#的时间到Javascript的时间的转换
+        /// </summary>
+        /// <param name="TheDate">C#的时间</param>
+        /// <returns>Javascript的时间</returns>
+        public static long CsharpTime2JavascriptTime(this System.DateTime TheDate)
+        {
+            //string time = (System.DateTime.Now.Subtract(Convert.ToDateTime("1970-01-01 8:0:0"))).TotalMilliseconds.ToString();
+            //long d = MilliTimeStamp(DateTime.Now);
+
+            System.DateTime d1 = new System.DateTime(1970, 1, 1);
+            System.DateTime d2 = TheDate.ToUniversalTime();
+            TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
+
+            return (long)ts.TotalMilliseconds;
+        }
+
+        /// <summary>
+        /// PHP的时间转换成C#中的DateTime
+        /// </summary>
+        /// <param name="time">php的时间</param>
+        /// <returns>C#的时间</returns>
+        public static System.DateTime PhpTime2CsharpTime(long time)
+        {
+            System.DateTime timeStamp = new System.DateTime(1970, 1, 1);  //得到1970年的时间戳
+            long t = (time + 8 * 60 * 60) * 10000000 + timeStamp.Ticks;
+            System.DateTime dt = new System.DateTime(t);
+            return dt;
+        }
+
+        /// <summary>
+        ///  C#中的DateTime转换成PHP的时间
+        /// </summary>
+        /// <param name="time">C#时间</param>
+        /// <returns>php时间</returns>
+        public static long CsharpTime2PhpTime(this System.DateTime time)
+        {
+            System.DateTime timeStamp = new System.DateTime(1970, 1, 1);  //得到1970年的时间戳
+            long a = (System.DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000;  //注意这里有时区问题,用now就要减掉8个小时
+            return a;
+        }
+        #endregion
+
+        #region Rss日期时间转换,将时间全部转换为GMT时间
+        /// <summary> 
+        /// Rss日期时间转换,将时间全部转换为GMT时间 
+        /// </summary> 
+        /// <param name="strDateTime">Rss中读取的时间</param> 
+        /// <returns>处理后的标准时间格式</returns> 
+        public static string dateConvert(string strDateTime)
+        {
+            strDateTime = strDateTime.Replace("+0000", "GMT");
+            strDateTime = strDateTime.Replace("+0100", "GMT");
+            strDateTime = strDateTime.Replace("+0200", "GMT");
+            strDateTime = strDateTime.Replace("+0300", "GMT");
+            strDateTime = strDateTime.Replace("+0400", "GMT");
+            strDateTime = strDateTime.Replace("+0500", "GMT");
+            strDateTime = strDateTime.Replace("+0600", "GMT");
+            strDateTime = strDateTime.Replace("+0700", "GMT");
+            strDateTime = strDateTime.Replace("+0800", "GMT");
+            strDateTime = strDateTime.Replace("-0000", "GMT");
+            strDateTime = strDateTime.Replace("-0100", "GMT");
+            strDateTime = strDateTime.Replace("-0200", "GMT");
+            strDateTime = strDateTime.Replace("-0300", "GMT");
+            strDateTime = strDateTime.Replace("-0400", "GMT");
+            strDateTime = strDateTime.Replace("-0500", "GMT");
+            strDateTime = strDateTime.Replace("-0600", "GMT");
+            strDateTime = strDateTime.Replace("-0700", "GMT");
+            strDateTime = strDateTime.Replace("-0800", "GMT");
+            System.DateTime dt = System.DateTime.Parse(strDateTime, null, System.Globalization.DateTimeStyles.AdjustToUniversal);
+            return dt.ToString();
+        }
+        #endregion
+
+    }
+}

+ 400 - 0
Masuit.Tools/Files/Compress.cs

@@ -0,0 +1,400 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Threading.Tasks;
+using ICSharpCode.SharpZipLib.Checksums;
+using ICSharpCode.SharpZipLib.Zip;
+using Microsoft.Win32;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// SharpZip
+    /// </summary>
+    public static class SharpZip
+    {
+        #region 文件压缩
+
+        /// <summary>
+        /// 文件压缩
+        /// </summary> 
+        /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
+        /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
+        public static void PackFiles(string filename, string directory)
+        {
+            try
+            {
+                FastZip fz = new FastZip();
+                fz.CreateEmptyDirectories = true;
+                fz.CreateZip(filename, directory, true, "");
+                fz = null;
+            }
+            catch (Exception)
+            {
+                throw;
+            }
+        }
+
+        /// <summary>
+        /// 文件压缩
+        /// </summary> 
+        /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
+        /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
+        public static async void PackFilesAsync(string filename, string directory)
+        {
+            try
+            {
+                FastZip fz = new FastZip();
+                fz.CreateEmptyDirectories = true;
+                await Task.Run(() =>
+                {
+                    fz.CreateZip(filename, directory, true, "");
+                    fz = null;
+                }).ConfigureAwait(false);
+            }
+            catch (Exception)
+            {
+                throw;
+            }
+        }
+
+        #endregion
+
+        #region 文件解压缩
+
+        /// <summary>
+        /// 文件解压缩
+        /// </summary>
+        /// <param name="file">待解压文件名(包含物理路径)</param>
+        /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
+        public static bool UnpackFiles(string file, string dir)
+        {
+            if (!Directory.Exists(dir))
+                Directory.CreateDirectory(dir);
+            using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))
+            {
+                ZipEntry theEntry;
+                while ((theEntry = s.GetNextEntry()) != null)
+                {
+                    string directoryName = Path.GetDirectoryName(theEntry.Name);
+                    string fileName = Path.GetFileName(theEntry.Name);
+                    if (directoryName != string.Empty)
+                        Directory.CreateDirectory(dir + directoryName);
+                    if (fileName != string.Empty)
+                    {
+                        using (FileStream streamWriter = File.Create(dir + theEntry.Name))
+                        {
+                            int size = 2048;
+                            byte[] data = new byte[2048];
+                            while (true)
+                            {
+                                size = s.Read(data, 0, data.Length);
+                                if (size > 0)
+                                    streamWriter.Write(data, 0, size);
+                                else
+                                    break;
+                            }
+                        }
+                    }
+                }
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// 文件解压缩
+        /// </summary>
+        /// <param name="file">待解压文件名(包含物理路径)</param>
+        /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
+        public static async Task<bool> UnpackFilesAsync(string file, string dir)
+        {
+            if (!Directory.Exists(dir))
+                Directory.CreateDirectory(dir);
+            using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))
+            {
+                ZipEntry theEntry;
+                await Task.Run(() =>
+                {
+                    while ((theEntry = s.GetNextEntry()) != null)
+                    {
+                        string directoryName = Path.GetDirectoryName(theEntry.Name);
+                        string fileName = Path.GetFileName(theEntry.Name);
+                        if (directoryName != string.Empty)
+                            Directory.CreateDirectory(dir + directoryName);
+                        if (fileName != string.Empty)
+                        {
+                            using (FileStream streamWriter = File.Create(dir + theEntry.Name))
+                            {
+                                int size = 2048;
+                                byte[] data = new byte[2048];
+                                while (true)
+                                {
+                                    size = s.Read(data, 0, data.Length);
+                                    if (size > 0)
+                                        streamWriter.Write(data, 0, size);
+                                    else
+                                        break;
+                                }
+                            }
+                        }
+                    }
+                }).ConfigureAwait(false);
+            }
+            return true;
+        }
+
+        #endregion
+    }
+
+    /// <summary>
+    /// ClassZip
+    /// </summary>
+    public static class ClassZip
+    {
+        #region 压缩
+
+        /// <summary>
+        /// 压缩
+        /// </summary>
+        /// <param name="FileToZip">待压缩的文件目录</param>
+        /// <param name="ZipedFile">生成的目标文件</param>
+        /// <param name="level">压缩等级,默认值6</param>
+        public static bool Zip(string FileToZip, string ZipedFile, int level = 6)
+        {
+            if (Directory.Exists(FileToZip))
+                return ZipFileDictory(FileToZip, ZipedFile, level);
+            if (File.Exists(FileToZip))
+                return ZipFile(FileToZip, ZipedFile, level);
+            return false;
+        }
+
+        #endregion
+
+        #region 解压
+
+        /// <summary>
+        /// 解压
+        /// </summary>
+        /// <param name="FileToUpZip">待解压的文件</param>
+        /// <param name="ZipedFolder">解压目标存放目录</param>
+        public static void UnZip(string FileToUpZip, string ZipedFolder)
+        {
+            if (!File.Exists(FileToUpZip))
+                return;
+            if (!Directory.Exists(ZipedFolder))
+                Directory.CreateDirectory(ZipedFolder);
+            ZipEntry theEntry = null;
+            string fileName;
+            using (ZipInputStream s = new ZipInputStream(File.OpenRead(FileToUpZip)))
+            {
+                while ((theEntry = s.GetNextEntry()) != null)
+                {
+                    if (theEntry.Name != string.Empty)
+                    {
+                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
+                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
+                        {
+                            Directory.CreateDirectory(fileName);
+                            continue;
+                        }
+                        using (FileStream streamWriter = File.Create(fileName))
+                        {
+                            int size = 2048;
+                            byte[] data = new byte[2048];
+                            while (true)
+                            {
+                                size = s.Read(data, 0, data.Length);
+                                if (size > 0)
+                                    streamWriter.Write(data, 0, size);
+                                else
+                                    break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        #endregion
+
+        #region 私有方法
+
+        #region 递归压缩文件夹方法
+
+        /// <summary>
+        /// 递归压缩文件夹方法
+        /// </summary>
+        /// <param name="folderToZip">需要压缩的文件夹</param>
+        /// <param name="s">压缩流</param>
+        /// <param name="parentFolderName">父级文件夹</param>
+        private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
+        {
+            bool res = true;
+            string[] folders, filenames;
+            ZipEntry entry = null;
+            Crc32 crc = new Crc32();
+            entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
+            s.PutNextEntry(entry);
+            s.Flush();
+            filenames = Directory.GetFiles(folderToZip);
+            foreach (string file in filenames)
+            {
+                using (FileStream fs = File.OpenRead(file))
+                {
+                    byte[] buffer = new byte[fs.Length];
+                    fs.Read(buffer, 0, buffer.Length);
+                    entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
+                    entry.DateTime = DateTime.Now;
+                    entry.Size = fs.Length;
+                    fs.Close();
+                    crc.Reset();
+                    crc.Update(buffer);
+                    entry.Crc = crc.Value;
+                    s.PutNextEntry(entry);
+                    s.Write(buffer, 0, buffer.Length);
+                }
+            }
+            folders = Directory.GetDirectories(folderToZip);
+            foreach (string folder in folders)
+            {
+                if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip))))
+                    return false;
+            }
+
+            return res;
+        }
+
+        #endregion
+
+        #region 压缩目录
+
+        /// <summary>
+        /// 压缩目录
+        /// </summary>
+        /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
+        /// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
+        /// <param name="level">压缩等级</param>
+        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
+        {
+            bool res;
+            if (!Directory.Exists(FolderToZip))
+                return false;
+            using (ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile)))
+            {
+                s.SetLevel(level);
+                res = ZipFileDictory(FolderToZip, s, "");
+                s.Finish();
+            }
+            return res;
+        }
+
+        #endregion
+
+        #region 压缩文件
+
+        /// <summary>
+        /// 压缩文件
+        /// </summary>
+        /// <param name="fileToZip">要进行压缩的文件名</param>
+        /// <param name="zipedFile">压缩后生成的压缩文件名</param>
+        /// <param name="level">压缩等级</param>
+        /// <exception cref="FileNotFoundException"></exception>
+        private static bool ZipFile(string fileToZip, string zipedFile, int level)
+        {
+            if (!File.Exists(fileToZip))
+                throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
+            ZipEntry ZipEntry = null;
+            bool res = true;
+            FileStream ZipFile = File.OpenRead(fileToZip);
+            byte[] buffer = new byte[ZipFile.Length];
+            ZipFile.Read(buffer, 0, buffer.Length);
+            ZipFile = File.Create(zipedFile);
+            using (ZipFile)
+            {
+                using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
+                {
+                    ZipEntry = new ZipEntry(Path.GetFileName(fileToZip));
+                    ZipStream.PutNextEntry(ZipEntry);
+                    ZipStream.SetLevel(level);
+                    ZipStream.Write(buffer, 0, buffer.Length);
+                }
+            }
+            return res;
+        }
+
+        #endregion
+
+        #endregion
+    }
+
+    /// <summary>
+    /// WinRAR压缩操作
+    /// </summary>
+    public static class ZipHelper
+    {
+        #region 压缩
+
+        /// <summary>
+        /// 压缩
+        /// </summary>
+        /// <param name="zipname">要解压的文件名</param>
+        /// <param name="zippath">要压缩的文件目录</param>
+        /// <param name="dirpath">初始目录</param>
+        public static void EnZip(string zipname, string zippath, string dirpath)
+        {
+            the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
+            the_Obj = the_Reg.GetValue("");
+            the_rar = the_Obj.ToString();
+            the_Reg.Close();
+            the_rar = the_rar.Substring(1, the_rar.Length - 7);
+            the_Info = " a  " + zipname + " " + zippath;
+            the_StartInfo = new ProcessStartInfo();
+            the_StartInfo.FileName = the_rar;
+            the_StartInfo.Arguments = the_Info;
+            the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
+            the_StartInfo.WorkingDirectory = dirpath;
+            the_Process = new Process();
+            the_Process.StartInfo = the_StartInfo;
+            the_Process.Start();
+        }
+
+        #endregion
+
+        #region 解压缩
+
+        /// <summary>
+        /// 解压缩
+        /// </summary>
+        /// <param name="zipname">要解压的文件名</param>
+        /// <param name="zippath">要解压的文件路径</param>
+        public static void DeZip(string zipname, string zippath)
+        {
+            the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
+            the_Obj = the_Reg.GetValue("");
+            the_rar = the_Obj.ToString();
+            the_Reg.Close();
+            the_rar = the_rar.Substring(1, the_rar.Length - 7);
+            the_Info = " X " + zipname + " " + zippath;
+            the_StartInfo = new ProcessStartInfo();
+            the_StartInfo.FileName = the_rar;
+            the_StartInfo.Arguments = the_Info;
+            the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
+            the_Process = new Process();
+            the_Process.StartInfo = the_StartInfo;
+            the_Process.Start();
+        }
+
+        #endregion
+
+        #region 私有变量
+
+        private static string the_rar;
+        private static RegistryKey the_Reg;
+        private static object the_Obj;
+        private static string the_Info;
+        private static ProcessStartInfo the_StartInfo;
+        private static Process the_Process;
+
+        #endregion
+    }
+}

+ 143 - 0
Masuit.Tools/Files/DocumentConvert.cs

@@ -0,0 +1,143 @@
+using System.IO;
+using System.Threading.Tasks;
+using Aspose.Words;
+using Masuit.Tools.Models;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// 文档转换操作
+    /// </summary>
+    public static class DocumentConvert
+    {
+        static DocumentConvert()
+        {
+            AsposeLicense.ActivateMemoryPatching();
+        }
+
+        #region doc转html
+
+        /// <summary>
+        /// doc转html
+        /// </summary>
+        /// <param name="docPath">doc文件路径</param>
+        /// <param name="htmlDir">生成的html所在目录,由于生成html后会将图片都放到同级的目录下,所以用文件夹保存,默认的html文件名为index.html</param>
+        /// <param name="index">默认文档名为index.html</param>
+        public static void Doc2Html(string docPath, string htmlDir, string index = "index.html")
+        {
+            Document doc = new Document(docPath);
+            doc.Save(Path.Combine(htmlDir, index), SaveFormat.Html);
+        }
+
+        /// <summary>
+        /// doc转html
+        /// </summary>
+        /// <param name="docPath">doc文件路径</param>
+        /// <param name="htmlDir">生成的html所在目录,由于生成html后会将图片都放到同级的目录下,所以用文件夹保存,默认的html文件名为index.html</param>
+        /// <param name="index">默认文档名为index.html</param>
+        public static async void Doc2HtmlAsync(string docPath, string htmlDir, string index = "index.html")
+        {
+            Document doc = new Document(docPath);
+            await Task.Run(() => doc.Save(Path.Combine(htmlDir, index), SaveFormat.Html)).ConfigureAwait(true);
+        }
+
+        #endregion
+
+        #region doc转pdf
+
+        /// <summary>
+        /// doc转pdf
+        /// </summary>
+        /// <param name="docPath">doc源文件</param>
+        /// <param name="pdfPath">目标pdf文件</param>
+        /// <param name="paperSize">纸张大小</param>
+        /// <param name="leftMargin">左边距</param>
+        /// <param name="rightMargin">右边距</param>
+        /// <param name="topMargin">上边距</param>
+        /// <param name="bottomMargin">下边距</param>
+        public static void Doc2Pdf(string docPath, string pdfPath, PaperSize paperSize = PaperSize.A4, double leftMargin = 20, double rightMargin = 20, double topMargin = 20, double bottomMargin = 20)
+        {
+            Document doc = new Document(docPath);
+            PageSetup pageSetup = new DocumentBuilder(doc).PageSetup;
+            pageSetup.PaperSize = paperSize;
+            pageSetup.LeftMargin = leftMargin;
+            pageSetup.RightMargin = rightMargin;
+            pageSetup.TopMargin = topMargin;
+            pageSetup.BottomMargin = bottomMargin;
+            doc.Save(pdfPath, SaveFormat.Pdf);
+        }
+
+        /// <summary>
+        /// doc转pdf
+        /// </summary>
+        /// <param name="docPath">doc源文件</param>
+        /// <param name="pdfPath">目标pdf文件</param>
+        /// <param name="paperSize">纸张大小</param>
+        /// <param name="leftMargin">左边距</param>
+        /// <param name="rightMargin">右边距</param>
+        /// <param name="topMargin">上边距</param>
+        /// <param name="bottomMargin">下边距</param>
+        public static async void Doc2PdfAsync(string docPath, string pdfPath, PaperSize paperSize = PaperSize.A4, double leftMargin = 20, double rightMargin = 20, double topMargin = 20, double bottomMargin = 20)
+        {
+            Document doc = new Document(docPath);
+            PageSetup pageSetup = new DocumentBuilder(doc).PageSetup;
+            pageSetup.PaperSize = paperSize;
+            pageSetup.LeftMargin = leftMargin;
+            pageSetup.RightMargin = rightMargin;
+            pageSetup.TopMargin = topMargin;
+            pageSetup.BottomMargin = bottomMargin;
+            await Task.Run(() => doc.Save(pdfPath, SaveFormat.Pdf)).ConfigureAwait(false);
+        }
+
+        #endregion
+
+        #region html转Word
+
+        /// <summary>
+        /// html转Word
+        /// </summary>
+        /// <param name="htmlPath">html源文件</param>
+        /// <param name="docPath">目标doc文件</param>
+        /// <param name="paperSize">纸张大小,默认A4纸</param>
+        /// <param name="leftMargin">左边距,默认10</param>
+        /// <param name="rightMargin">右边距,默认10</param>
+        /// <param name="topMargin">上边距,默认10</param>
+        /// <param name="bottomMargin">下边距,默认10</param>
+        public static void Html2Word(string htmlPath, string docPath, PaperSize paperSize = PaperSize.A4, double leftMargin = 20, double rightMargin = 20, double topMargin = 20, double bottomMargin = 20)
+        {
+            Document doc = new Document(htmlPath);
+            PageSetup pageSetup = new DocumentBuilder(doc).PageSetup;
+            pageSetup.PaperSize = paperSize;
+            pageSetup.LeftMargin = leftMargin;
+            pageSetup.RightMargin = rightMargin;
+            pageSetup.TopMargin = topMargin;
+            pageSetup.BottomMargin = bottomMargin;
+            doc.Save(docPath, SaveFormat.Doc);
+        }
+
+        /// <summary>
+        /// html转Word
+        /// </summary>
+        /// <param name="htmlPath">html源文件</param>
+        /// <param name="docPath">目标doc文件</param>
+        /// <param name="paperSize">纸张大小,默认A4纸</param>
+        /// <param name="leftMargin">左边距,默认10</param>
+        /// <param name="rightMargin">右边距,默认10</param>
+        /// <param name="topMargin">上边距,默认10</param>
+        /// <param name="bottomMargin">下边距,默认10</param>
+        public static async void Html2WordAsync(string htmlPath, string docPath, PaperSize paperSize = PaperSize.A4, double leftMargin = 20, double rightMargin = 20, double topMargin = 20, double bottomMargin = 20)
+        {
+            Document doc = new Document(htmlPath);
+            PageSetup pageSetup = new DocumentBuilder(doc).PageSetup;
+            pageSetup.PaperSize = paperSize;
+            pageSetup.LeftMargin = leftMargin;
+            pageSetup.RightMargin = rightMargin;
+            pageSetup.TopMargin = topMargin;
+            pageSetup.BottomMargin = bottomMargin;
+            await Task.Run(() => doc.Save(docPath, SaveFormat.Doc)).ConfigureAwait(false);
+        }
+
+        #endregion
+
+    }
+}

+ 60 - 0
Masuit.Tools/Files/ExtensionAttach.cs

@@ -0,0 +1,60 @@
+using Microsoft.Win32;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// 文件关联
+    /// </summary>
+    public static class ExtensionAttach
+    {
+        /// <summary>
+        /// 关联文件
+        /// </summary>
+        /// <param name="filePathString">应用程序路径</param>
+        /// <param name="pFileTypeName">文件类型</param>
+        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>
+        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");
+            }
+        }
+    }
+}

+ 178 - 0
Masuit.Tools/Files/FileExt.cs

@@ -0,0 +1,178 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// 大文件操作扩展类
+    /// </summary>
+    public static class FileExt
+    {
+        /// <summary>
+        /// 以文件流的形式复制大文件
+        /// </summary>
+        /// <param name="fs">源</param>
+        /// <param name="dest">目标地址</param>
+        public static void CopyToFile(this Stream fs, string dest)
+        {
+            using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            {
+                byte[] buf = new byte[1024 * 1024 * 8];
+                int len = 0;
+                while ((len = fs.Read(buf, 0, buf.Length)) != 0)
+                    fsWrite.Write(buf, 0, len);
+            }
+        }
+
+        /// <summary>
+        /// 以文件流的形式复制大文件(异步方式)
+        /// </summary>
+        /// <param name="fs">源</param>
+        /// <param name="dest">目标地址</param>
+        public static async void CopyToFileAsync(this Stream fs, string dest)
+        {
+            using (FileStream fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            {
+                byte[] buf = new byte[1024 * 1024 * 8];
+                int len = 0;
+                await Task.Run(() =>
+                {
+                    while ((len = fs.Read(buf, 0, buf.Length)) != 0)
+                        fsWrite.Write(buf, 0, len);
+                }).ConfigureAwait(false);
+            }
+        }
+
+        /// <summary>
+        /// 计算文件的 MD5 值
+        /// </summary>
+        /// <param name="fs">源文件流</param>
+        /// <returns>MD5 值16进制字符串</returns>
+        public static string GetFileMD5(this FileStream fs)
+        {
+            return HashFile(fs, "md5");
+        }
+
+        /// <summary>
+        /// 计算文件的 MD5 值
+        /// </summary>
+        /// <param name="fs">源文件流</param>
+        /// <returns>MD5 值16进制字符串</returns>
+        public static Task<string> GetFileMD5Async(this FileStream fs)
+        {
+            return HashFileAsync(fs, "md5");
+        }
+
+        /// <summary>
+        /// 计算文件的 sha1 值
+        /// </summary>
+        /// <param name="fs">源文件流</param>
+        /// <returns>sha1 值16进制字符串</returns>
+        public static string GetFileSha1(this Stream fs)
+        {
+            return HashFile(fs, "sha1");
+        }
+
+        /// <summary>
+        /// 计算文件的 sha1 值
+        /// </summary>
+        /// <param name="fs">源文件流</param>
+        /// <returns>sha1 值16进制字符串</returns>
+        public static Task<string> GetFileSha1Async(this FileStream fs)
+        {
+            return HashFileAsync(fs, "sha1");
+        }
+
+        /// <summary>
+        /// 计算文件的哈希值
+        /// </summary>
+        /// <param name="fs">被操作的源数据流</param>
+        /// <param name="algName">算法:sha1,md5</param>
+        /// <returns>哈希值16进制字符串</returns>
+        private static string HashFile(Stream fs, string algName)
+        {
+            byte[] hashBytes = HashData(fs, algName);
+            return ByteArrayToHexString(hashBytes);
+        }
+
+        /// <summary>
+        /// 计算文件的哈希值
+        /// </summary>
+        /// <param name="fs">被操作的源数据流</param>
+        /// <param name="algName">算法:sha1,md5</param>
+        /// <returns>哈希值16进制字符串</returns>
+        private static async Task<string> HashFileAsync(Stream fs, string algName)
+        {
+            byte[] hashBytes = await HashDataAsync(fs, algName).ConfigureAwait(false);
+            return ByteArrayToHexString(hashBytes);
+        }
+
+        /// <summary>
+        /// 计算哈希值
+        /// </summary>
+        /// <param name="stream">要计算哈希值的 Stream</param>
+        /// <param name="algName">算法:sha1,md5</param>
+        /// <returns>哈希值字节数组</returns>
+        private static byte[] HashData(System.IO.Stream stream, string algName)
+        {
+            System.Security.Cryptography.HashAlgorithm algorithm;
+            if (algName == null)
+            {
+                throw new ArgumentNullException("algName 不能为 null");
+            }
+            if (string.Compare(algName, "sha1", true) == 0)
+            {
+                algorithm = System.Security.Cryptography.SHA1.Create();
+            }
+            else
+            {
+                if (string.Compare(algName, "md5", true) != 0)
+                {
+                    throw new Exception("algName 只能使用 sha1 或 md5");
+                }
+                algorithm = System.Security.Cryptography.MD5.Create();
+            }
+            return algorithm.ComputeHash(stream);
+        }
+
+        /// <summary>
+        /// 计算哈希值
+        /// </summary>
+        /// <param name="stream">要计算哈希值的 Stream</param>
+        /// <param name="algName">算法:sha1,md5</param>
+        /// <returns>哈希值字节数组</returns>
+        private static async Task<byte[]> HashDataAsync(Stream stream, string algName)
+        {
+            System.Security.Cryptography.HashAlgorithm algorithm;
+            if (algName == null)
+            {
+                throw new ArgumentNullException("algName 不能为 null");
+            }
+            if (string.Compare(algName, "sha1", true) == 0)
+            {
+                algorithm = System.Security.Cryptography.SHA1.Create();
+            }
+            else
+            {
+                if (string.Compare(algName, "md5", true) != 0)
+                {
+                    throw new Exception("algName 只能使用 sha1 或 md5");
+                }
+                algorithm = System.Security.Cryptography.MD5.Create();
+            }
+            return await Task.Run(() => algorithm.ComputeHash(stream)).ConfigureAwait(false);
+
+        }
+
+        /// <summary>
+        /// 字节数组转换为16进制表示的字符串
+        /// </summary>
+        private static string ByteArrayToHexString(byte[] buf)
+        {
+            return BitConverter.ToString(buf).Replace("-", "");
+        }
+
+
+    }
+}

+ 152 - 0
Masuit.Tools/Files/FileTree.cs

@@ -0,0 +1,152 @@
+using System.IO;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// 文件目录树操作
+    /// </summary>
+    public static class FileTree
+    {
+        #region 获取指定文件夹下所有子目录及文件(树形)
+
+        /// <summary>
+        /// 获取指定文件夹下所有子目录及文件
+        /// </summary>
+        /// <param name="Path">详细路径</param>
+        public static string GetFoldAll(string Path)
+        {
+            string str = "";
+            DirectoryInfo thisOne = new DirectoryInfo(Path);
+            str = ListTreeShow(thisOne, 0, str);
+            return str;
+        }
+
+        /// <summary>
+        /// 获取指定文件夹下所有子目录及文件函数
+        /// </summary>
+        /// <param name="theDir">指定目录</param>
+        /// <param name="nLevel">默认起始值,调用时,一般为0</param>
+        /// <param name="Rn">用于迭加的传入值,一般为空</param>
+        /// <returns></returns>
+        public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn)//递归目录 文件
+        {
+            DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
+            foreach (DirectoryInfo dirinfo in subDirectories)
+            {
+                if (nLevel == 0)
+                {
+                    Rn += "├";
+                }
+                else
+                {
+                    string _s = "";
+                    for (int i = 1; i <= nLevel; i++)
+                    {
+                        _s += "│&nbsp;";
+                    }
+                    Rn += _s + "├";
+                }
+                Rn += "<b>" + dirinfo.Name + "</b><br />";
+                FileInfo[] fileInfo = dirinfo.GetFiles();   //目录下的文件
+                foreach (FileInfo fInfo in fileInfo)
+                {
+                    if (nLevel == 0)
+                    {
+                        Rn += "│&nbsp;├";
+                    }
+                    else
+                    {
+                        string _f = "";
+                        for (int i = 1; i <= nLevel; i++)
+                        {
+                            _f += "│&nbsp;";
+                        }
+                        Rn += _f + "│&nbsp;├";
+                    }
+                    Rn += fInfo.Name + " <br />";
+                }
+                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn);
+            }
+            return Rn;
+        }
+
+        /// <summary>
+        /// 获取指定文件夹下所有子目录及文件(下拉框形)
+        /// </summary>
+        /// <param name="Path">详细路径</param>
+        ///<param name="DropName">下拉列表名称</param>
+        ///<param name="tplPath">默认选择模板名称</param>
+        public static string GetFoldAll(string Path, string DropName, string tplPath)
+        {
+            string strDrop = "<select name=\"" + DropName + "\" id=\"" + DropName + "\"><option value=\"\">--请选择详细模板--</option>";
+            string str = "";
+            DirectoryInfo thisOne = new DirectoryInfo(Path);
+            str = ListTreeShow(thisOne, 0, str, tplPath);
+            return strDrop + str + "</select>";
+        }
+
+        /// <summary>
+        /// 获取指定文件夹下所有子目录及文件函数
+        /// </summary>
+        /// <param name="theDir">指定目录</param>
+        /// <param name="nLevel">默认起始值,调用时,一般为0</param>
+        /// <param name="Rn">用于迭加的传入值,一般为空</param>
+        /// <param name="tplPath">默认选择模板名称</param>
+        /// <returns></returns>
+        public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn, string tplPath)//递归目录 文件
+        {
+            DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
+
+            foreach (DirectoryInfo dirinfo in subDirectories)
+            {
+                Rn += "<option value=\"" + dirinfo.Name + "\"";
+                if (string.Equals(tplPath, dirinfo.Name, System.StringComparison.CurrentCultureIgnoreCase))
+                {
+                    Rn += " selected ";
+                }
+                Rn += ">";
+                if (nLevel == 0)
+                {
+                    Rn += "┣";
+                }
+                else
+                {
+                    string _s = "";
+                    for (int i = 1; i <= nLevel; i++)
+                    {
+                        _s += "│&nbsp;";
+                    }
+                    Rn += _s + "┣";
+                }
+                Rn += "" + dirinfo.Name + "</option>";
+                FileInfo[] fileInfo = dirinfo.GetFiles();   //目录下的文件
+                foreach (FileInfo fInfo in fileInfo)
+                {
+                    Rn += "<option value=\"" + dirinfo.Name + "/" + fInfo.Name + "\"";
+                    if (string.Equals(tplPath, fInfo.Name, System.StringComparison.CurrentCultureIgnoreCase))
+                    {
+                        Rn += " selected ";
+                    }
+                    Rn += ">";
+                    if (nLevel == 0)
+                    {
+                        Rn += "│&nbsp;├";
+                    }
+                    else
+                    {
+                        string _f = "";
+                        for (int i = 1; i <= nLevel; i++)
+                        {
+                            _f += "│&nbsp;";
+                        }
+                        Rn += _f + "│&nbsp;├";
+                    }
+                    Rn += fInfo.Name + "</option>";
+                }
+                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn, tplPath);
+            }
+            return Rn;
+        }
+        #endregion
+    }
+}

+ 89 - 0
Masuit.Tools/Files/INIFile.cs

@@ -0,0 +1,89 @@
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace Masuit.Tools.Files
+{
+    /// <summary>
+    /// INI文件操作辅助类
+    /// </summary>
+    public class INIFile
+    {
+        /// <summary>
+        /// 文件路径
+        /// </summary>
+        public readonly string path;
+
+        /// <summary>
+        /// 传入INI文件路径构造对象
+        /// </summary>
+        /// <param name="INIPath">INI文件路径</param>
+        public INIFile(string INIPath)
+        {
+            path = INIPath;
+        }
+
+        [DllImport("kernel32")]
+        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
+
+        [DllImport("kernel32")]
+        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
+
+        [DllImport("kernel32")]
+        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
+
+        /// <summary>
+        /// 写INI文件
+        /// </summary>
+        /// <param name="Section">分组节点</param>
+        /// <param name="Key">关键字</param>
+        /// <param name="Value">值</param>
+        public void IniWriteValue(string Section, string Key, string Value)
+        {
+            WritePrivateProfileString(Section, Key, Value, this.path);
+        }
+
+        /// <summary>
+        /// 读取INI文件
+        /// </summary>
+        /// <param name="Section">分组节点</param>
+        /// <param name="Key">关键字</param>
+        /// <returns>值</returns>
+        public string IniReadValue(string Section, string Key)
+        {
+            StringBuilder temp = new StringBuilder(255);
+            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
+            return temp.ToString();
+        }
+
+        /// <summary>
+        /// 读取INI文件
+        /// </summary>
+        /// <param name="section">分组节点</param>
+        /// <param name="key">关键字</param>
+        /// <returns>值的字节表现形式</returns>
+        public byte[] IniReadValues(string section, string key)
+        {
+            byte[] temp = new byte[255];
+            int i = GetPrivateProfileString(section, key, "", temp, 255, this.path);
+            return temp;
+        }
+
+        /// <summary>
+        /// 删除ini文件下所有段落
+        /// </summary>
+        public void ClearAllSection()
+        {
+            IniWriteValue(null, null, null);
+        }
+
+        /// <summary>
+        /// 删除ini文件下指定段落下的所有键
+        /// </summary>
+        /// <param name="Section">分组节点</param>
+        public void ClearSection(string Section)
+        {
+            IniWriteValue(Section, null, null);
+        }
+    }
+}

+ 467 - 0
Masuit.Tools/Hardware/SystemInfo.cs

@@ -0,0 +1,467 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Management;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Web.Script.Serialization;
+using ConDep.Dsl.Config;
+
+namespace Masuit.Tools.Hardware
+{
+    /// <summary>
+    /// 硬件信息
+    /// </summary>
+    public static class SystemInfo
+    {
+        private const int GW_HWNDFIRST = 0;
+        private const int GW_HWNDNEXT = 2;
+        private const int GWL_STYLE = -16;
+        private const int WS_VISIBLE = 268435456;
+        private const int WS_BORDER = 8388608;
+        private static readonly PerformanceCounter pcCpuLoad; //CPU计数器 
+
+        #region 构造函数 
+
+        /// <summary>
+        /// 静态构造函数
+        /// </summary>
+        static SystemInfo()
+        {
+            //初始化CPU计数器 
+            pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
+            pcCpuLoad.MachineName = ".";
+            pcCpuLoad.NextValue();
+
+            //CPU个数 
+            ProcessorCount = Environment.ProcessorCount;
+
+            //获得物理内存 
+            ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
+            ManagementObjectCollection moc = mc.GetInstances();
+            foreach (ManagementObject mo in moc)
+            {
+                if (mo["TotalPhysicalMemory"] != null)
+                {
+                    PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
+                }
+            }
+        }
+
+        #endregion
+
+        #region CPU核心 
+
+        /// <summary>
+        /// 获取CPU核心数 
+        /// </summary>
+        public static int ProcessorCount { get; }
+
+        #endregion
+
+        #region CPU占用率 
+
+        /// <summary>
+        /// 获取CPU占用率 %
+        /// </summary>
+        public static float CpuLoad
+        {
+            get { return pcCpuLoad.NextValue(); }
+        }
+
+        #endregion
+
+        #region 可用内存 
+
+        /// <summary>
+        /// 获取可用内存
+        /// </summary>
+        public static long MemoryAvailable
+        {
+            get
+            {
+                long availablebytes = 0;
+                ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
+                foreach (ManagementObject mo in mos.GetInstances())
+                {
+                    if (mo["FreePhysicalMemory"] != null)
+                        availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
+                }
+
+                return availablebytes;
+            }
+        }
+
+        #endregion
+
+        #region 物理内存 
+
+        /// <summary>
+        /// 获取物理内存
+        /// </summary>
+        public static long PhysicalMemory { get; }
+
+        #endregion
+
+        #region 查找所有应用程序标题 
+
+        /// <summary>
+        /// 查找所有应用程序标题 
+        /// </summary>
+        /// <param name="Handle">应用程序标题范型</param>
+        /// <returns>所有应用程序集合</returns>
+        public static ArrayList FindAllApps(int Handle)
+        {
+            ArrayList Apps = new ArrayList();
+
+            int hwCurr = GetWindow(Handle, GW_HWNDFIRST);
+
+            while (hwCurr > 0)
+            {
+                int IsTask = WS_VISIBLE | WS_BORDER;
+                int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
+                bool TaskWindow = (lngStyle & IsTask) == IsTask;
+                if (TaskWindow)
+                {
+                    int length = GetWindowTextLength(new IntPtr(hwCurr));
+                    StringBuilder sb = new StringBuilder(2 * length + 1);
+                    GetWindowText(hwCurr, sb, sb.Capacity);
+                    string strTitle = sb.ToString();
+                    if (!string.IsNullOrEmpty(strTitle))
+                        Apps.Add(strTitle);
+                }
+                hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
+            }
+
+            return Apps;
+        }
+
+        #endregion
+
+        #region 获取CPU的数量
+
+        /// <summary>
+        /// 获取CPU的数量
+        /// </summary>
+        /// <returns>CPU的数量</returns>
+        public static int GetCpuCount()
+        {
+            ManagementClass m = new ManagementClass("Win32_Processor");
+            ManagementObjectCollection mn = m.GetInstances();
+            return mn.Count;
+        }
+
+        #endregion
+
+        #region 获取CPU信息
+        /// <summary>
+        /// 获取CPU信息
+        /// </summary>
+        /// <returns>CPU信息</returns>
+        public static List<CpuInfo> GetCpuInfo()
+        {
+            List<CpuInfo> list = new List<CpuInfo>();
+            Dictionary<string, string> dic = new Dictionary<string, string>();
+            ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
+            foreach (ManagementObject MyObject in MySearcher.Get())
+            {
+                list.Add(new CpuInfo
+                {
+                    CpuLoad = CpuLoad,
+                    NumberOfLogicalProcessors = ProcessorCount,
+                    CurrentClockSpeed = MyObject.Properties["CurrentClockSpeed"].Value.ToString(),
+                    Manufacturer = MyObject.Properties["Manufacturer"].Value.ToString(),
+                    MaxClockSpeed = MyObject.Properties["MaxClockSpeed"].Value.ToString(),
+                    Type = MyObject.Properties["Name"].Value.ToString(),
+                    DataWidth = MyObject.Properties["DataWidth"].Value.ToString(),
+                    DeviceID = MyObject.Properties["DeviceID"].Value.ToString(),
+                    NumberOfCores = Convert.ToInt32(MyObject.Properties["NumberOfCores"].Value),
+                    Temperature = GetCPUTemperature()
+                });
+            }
+
+            return list;
+        }
+
+        #endregion
+
+        #region 获取内存信息
+
+        /// <summary>
+        /// 获取内存信息
+        /// </summary>
+        /// <returns>内存信息</returns>
+        public static RamInfo GetRamInfo()
+        {
+            MEMORY_INFO MemInfo = new MEMORY_INFO();
+            GlobalMemoryStatus(ref MemInfo);
+            return new RamInfo
+            {
+                MemoryAvailable = MemoryAvailable,
+                PhysicalMemory = PhysicalMemory,
+                TotalPageFile = MemInfo.dwTotalPageFile,
+                AvailablePageFile = MemInfo.dwAvailPageFile,
+                AvailableVirtual = MemInfo.dwAvailVirtual,
+                TotalVirtual = MemInfo.dwTotalVirtual
+            };
+        }
+
+        #endregion
+
+        #region 获取CPU温度
+        /// <summary>
+        /// 获取CPU温度
+        /// </summary>
+        /// <returns>CPU温度</returns>
+        public static double GetCPUTemperature()
+        {
+            string str = "";
+
+            ManagementObjectSearcher vManagementObjectSearcher = new ManagementObjectSearcher(@"root\WMI", @"select * from MSAcpi_ThermalZoneTemperature");
+
+            foreach (ManagementObject managementObject in vManagementObjectSearcher.Get())
+            {
+                string s = new JavaScriptSerializer().Serialize(managementObject.Properties);
+
+                str += managementObject.Properties["CurrentTemperature"].Value.ToString();
+            }
+
+            //这就是CPU的温度了
+            double temp = (double.Parse(str) - 2732) / 10;
+            return Math.Round(temp, 2);
+        }
+
+        #endregion
+
+        #region 定义CPU的信息结构
+
+        /// <summary>
+        /// 定义CPU的信息结构
+        /// </summary>
+        [StructLayout(LayoutKind.Sequential)]
+        public struct CPU_INFO
+        {
+#pragma warning disable 1591
+            public uint dwOemId;
+            public uint dwPageSize;
+            public uint lpMinimumApplicationAddress;
+            public uint lpMaximumApplicationAddress;
+            public uint dwActiveProcessorMask;
+            public uint dwNumberOfProcessors;
+            public uint dwProcessorType;
+            public uint dwAllocationGranularity;
+            public uint dwProcessorLevel;
+            public uint dwProcessorRevision;
+#pragma warning restore 1591
+        }
+
+        #endregion
+
+        #region 定义内存的信息结构
+
+        /// <summary>
+        /// 定义内存的信息结构
+        /// </summary>
+        [StructLayout(LayoutKind.Sequential)]
+        public struct MEMORY_INFO
+        {
+#pragma warning disable 1591
+            public uint dwLength;
+            public uint dwMemoryLoad;
+            public uint dwTotalPhys;
+            public uint dwAvailPhys;
+            public uint dwTotalPageFile;
+            public uint dwAvailPageFile;
+            public uint dwTotalVirtual;
+            public uint dwAvailVirtual;
+#pragma warning restore 1591
+        }
+
+        #endregion
+
+        #region 定义系统时间的信息结构
+
+        /// <summary>
+        /// 定义系统时间的信息结构
+        /// </summary>
+        [StructLayout(LayoutKind.Sequential)]
+        public struct SYSTEMTIME_INFO
+        {
+#pragma warning disable 1591
+            public ushort wYear;
+            public ushort wMonth;
+            public ushort wDayOfWeek;
+            public ushort wDay;
+            public ushort wHour;
+            public ushort wMinute;
+            public ushort wSecond;
+            public ushort wMilliseconds;
+#pragma warning restore 1591
+        }
+
+        #endregion
+
+        #region Win32API声明 
+#pragma warning disable 1591
+        [DllImport("kernel32")]
+        public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
+
+        [DllImport("kernel32")]
+        public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
+
+        [DllImport("kernel32")]
+        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
+
+        [DllImport("kernel32")]
+        public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);
+
+        [DllImport("kernel32")]
+        public static extern void GetSystemTime(ref SYSTEMTIME_INFO stinfo);
+
+        [DllImport("IpHlpApi.dll")]
+        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")]
+        public static extern int GetWindowLongA(int hWnd, int wIndx);
+
+        [DllImport("user32.dll")]
+        public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
+
+        [DllImport("user32", CharSet = CharSet.Auto)]
+        public static extern int GetWindowTextLength(IntPtr hWnd);
+#pragma warning restore 1591
+
+        #endregion
+
+        #region 获得分区信息 
+
+        /// <summary>
+        /// 获取分区信息
+        /// </summary>
+        /// <returns>分区信息</returns>
+        public static ArrayList GetLogicalDrives()
+        {
+            ArrayList drives = new ArrayList();
+            ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
+            ManagementObjectCollection disks = diskClass.GetInstances();
+            foreach (ManagementObject disk in disks)
+            {
+                if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed)
+                    drives.Add(new DiskInfo { Name = disk["Name"].ToString(), SizeInKb = long.Parse(disk["Size"].ToString()), FreeSpaceInKb = long.Parse(disk["FreeSpace"].ToString()) });
+            }
+
+            return drives;
+        }
+
+        /// <summary>
+        /// 获取特定分区信息
+        /// </summary>
+        /// <param name="DriverID">盘符</param>
+        /// <returns>特定分区信息</returns>
+        public static ArrayList GetLogicalDrives(char DriverID)
+        {
+            ArrayList drives = new ArrayList();
+            WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = ’" + DriverID + ":’");
+            ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery);
+            foreach (ManagementObject disk in wmifind.Get())
+            {
+                if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed)
+                    drives.Add(new DiskInfo { Name = disk["Name"].ToString(), SizeInKb = long.Parse(disk["Size"].ToString()), FreeSpaceInKb = long.Parse(disk["FreeSpace"].ToString()) });
+            }
+
+            return drives;
+        }
+
+        #endregion
+    }
+
+    #region CPU
+
+    /// <summary>
+    /// CPU模型
+    /// </summary>
+    public class CpuInfo
+    {
+        /// <summary>
+        /// 设备ID端口
+        /// </summary>
+        public string DeviceID { get; set; }
+
+        /// <summary>
+        /// CPU型号 
+        /// </summary>
+        public string Type { get; set; }
+
+        /// <summary>
+        /// CPU厂商
+        /// </summary>
+        public string Manufacturer { get; set; }
+
+        /// <summary>
+        /// CPU最大睿频
+        /// </summary>
+        public string MaxClockSpeed { get; set; }
+
+        /// <summary>
+        /// CPU的时钟频率
+        /// </summary>
+        public string CurrentClockSpeed { get; set; }
+
+        /// <summary>
+        /// CPU核心数
+        /// </summary>
+        public int NumberOfCores { get; set; }
+
+        /// <summary>
+        /// 逻辑处理器核心数
+        /// </summary>
+        public int NumberOfLogicalProcessors { get; set; }
+
+        /// <summary>
+        /// CPU使用率
+        /// </summary>
+        public double CpuLoad { get; set; }
+
+        /// <summary>
+        /// CPU位宽
+        /// </summary>
+        public string DataWidth { get; set; }
+
+        /// <summary>
+        /// 核心温度
+        /// </summary>
+        public double Temperature { get; set; }
+    }
+
+    #endregion
+
+    #region RAM
+
+    /// <summary>
+    /// 内存条模型
+    /// </summary>
+    public class RamInfo
+    {
+#pragma warning disable 1591
+        public double MemoryAvailable { get; set; }
+        public double PhysicalMemory { get; set; }
+        public double TotalPageFile { get; set; }
+        public double AvailablePageFile { get; set; }
+        public double TotalVirtual { get; set; }
+        public double AvailableVirtual { get; set; }
+
+        public double MemoryUsage
+        {
+            get { return (1 - MemoryAvailable / PhysicalMemory) * 100; }
+        }
+#pragma warning restore 1591
+    }
+
+    #endregion
+}

+ 865 - 0
Masuit.Tools/Html/HtmlHelper.cs

@@ -0,0 +1,865 @@
+using System;
+using System.IO;
+using System.IO.Compression;
+using System.Net;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Web;
+
+namespace Masuit.Tools.Html
+{
+    /// <summary>
+    ///1、获取HTML
+    ///1.1获取指定页面的HTML代码 GetHtml(string url, string postData, bool isPost, CookieContainer cookieContainer)
+    ///1.2获取HTMLGetHtml(string url, CookieContainer cookieContainer)
+    ///2、获取字符流
+    ///2.1获取字符流GetStream(string url, CookieContainer cookieContainer)
+    ///3、清除HTML标记 
+    ///3.1清除HTML标记  NoHTML(string Htmlstring)
+    ///4、匹配页面的链接 
+    ///4.1获取页面的链接正则 GetHref(string HtmlCode)
+    ///5、匹配页面的图片地址
+    /// 5.1匹配页面的图片地址 GetImgSrc(string HtmlCode, string imgHttp)
+    ///5.2匹配<img src="" />中的图片路径实际链接  GetImg(string ImgString, string imgHttp)
+    ///6、抓取远程页面内容
+    /// 6.1以GET方式抓取远程页面内容 Get_Http(string tUrl)
+    /// 6.2以POST方式抓取远程页面内容 Post_Http(string url, string postData, string encodeType)
+    ///7、压缩HTML输出
+    ///7.1压缩HTML输出 ZipHtml(string Html)
+    ///8、过滤HTML标签
+    /// 8.1过滤指定HTML标签 DelHtml(string s_TextStr, string html_Str)  
+    /// 8.2过滤HTML中的不安全标签 RemoveUnsafeHtml(string content)
+    /// HTML转行成TEXT HtmlToTxt(string strHtml)
+    /// 字符串转换为 HtmlStringToHtml(string str)
+    /// html转换成字符串HtmlToString(string strHtml)
+    /// 获取URL编码
+    /// 判断URL是否有效
+    /// 返回 HTML 字符串的编码解码结果
+    /// </summary>
+    public static class HtmlHelper
+    {
+        #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 int delay = 1000;
+        private static int currentTry = 0;
+        #endregion
+
+        #region 公有属性
+        /// <summary> 
+        /// Cookie容器
+        /// </summary> 
+        public static CookieContainer CookieContainer
+        {
+            get { return cc; }
+        }
+
+        /// <summary> 
+        /// 获取网页源码时使用的编码
+        /// </summary> 
+        public static Encoding Encoding { get; set; } = Encoding.GetEncoding("utf-8");
+
+        /// <summary>
+        /// 网络延迟
+        /// </summary>
+        public static int NetworkDelay
+        {
+            get
+            {
+                Random r = new Random();
+                return r.Next(delay, delay * 2);
+                // return (r.Next(delay / 1000, delay / 1000 * 2)) * 1000;
+            }
+            set { delay = value; }
+        }
+
+        /// <summary>
+        /// 最大尝试次数
+        /// </summary>
+        public static int MaxTry { get; set; } = 300;
+        #endregion
+
+        #region 1、获取HTML
+        /// <summary>
+        /// 1.1获取指定页面的HTML代码
+        /// </summary>
+        /// <param name="url">指定页面的路径</param>
+        /// <param name="postData">post 提交的字符串</param>
+        /// <param name="isPost">是否以post方式发送请求</param>
+        /// <param name="cookieContainer">Cookie集合</param>
+        public static string GetHtml(string url, string postData, bool isPost, CookieContainer cookieContainer)
+        {
+            if (string.IsNullOrEmpty(postData))
+            {
+                return GetHtml(url, cookieContainer);
+            }
+            Thread.Sleep(NetworkDelay);
+            currentTry++;
+            HttpWebRequest httpWebRequest = null;
+            HttpWebResponse httpWebResponse = null;
+            try
+            {
+                byte[] byteRequest = Encoding.Default.GetBytes(postData);
+
+                httpWebRequest = (HttpWebRequest)HttpWebRequest.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)
+                {
+                    httpWebResponse = (HttpWebResponse)ex.Response;
+                }
+                //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)
+                {
+                    GetHtml(url, postData, isPost, cookieContainer);
+                }
+                currentTry--;
+                if (httpWebRequest != null) httpWebRequest.Abort();
+                if (httpWebResponse != null) httpWebResponse.Close();
+                return string.Empty;
+            }
+        }
+
+        /// <summary>
+        /// 1.2获取HTML
+        /// </summary>
+        /// <param name="url">地址</param>
+        /// <param name="cookieContainer">Cookie集合</param>
+        public static string GetHtml(string url, CookieContainer cookieContainer)
+        {
+            Thread.Sleep(NetworkDelay);
+            currentTry++;
+            HttpWebRequest httpWebRequest = null;
+            HttpWebResponse httpWebResponse = null;
+            try
+            {
+                httpWebRequest = (HttpWebRequest)HttpWebRequest.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(url, cookieContainer);
+                currentTry--;
+                if (httpWebRequest != null) httpWebRequest.Abort();
+                if (httpWebResponse != null) httpWebResponse.Close();
+                return string.Empty;
+            }
+        }
+        #endregion
+
+        #region 2、获取字符流
+        /// <summary>
+        /// 2.1获取字符流
+        /// </summary>
+        ///---------------------------------------------------------------------------------------------------------------
+        /// 示例:
+        /// System.Net.CookieContainer cookie = new System.Net.CookieContainer(); 
+        /// Stream s = HttpHelper.GetStream("http://www.baidu.com", cookie);
+        /// picVerify.Image = Image.FromStream(s);
+        ///---------------------------------------------------------------------------------------------------------------
+        /// <param name="url">地址</param>
+        /// <param name="cookieContainer">cookieContainer</param>
+        public static Stream GetStream(string url, CookieContainer cookieContainer)
+        {
+            currentTry++;
+
+            HttpWebRequest httpWebRequest = null;
+            HttpWebResponse httpWebResponse = null;
+
+            try
+            {
+                httpWebRequest = (HttpWebRequest)HttpWebRequest.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)
+            {
+                if (currentTry <= MaxTry)
+                {
+                    GetHtml(url, cookieContainer);
+                }
+
+                currentTry--;
+
+                if (httpWebRequest != null)
+                {
+                    httpWebRequest.Abort();
+                }
+                if (httpWebResponse != null)
+                {
+                    httpWebResponse.Close();
+                }
+                return null;
+            }
+        }
+        #endregion
+
+        #region 3、清除HTML标记
+        ///<summary>   
+        ///3.1清除HTML标记   
+        ///</summary>   
+        ///<param name="Htmlstring">包括HTML的源码</param>   
+        ///<returns>已经去除后的文字</returns>   
+        public static string RemoveHTML(string Htmlstring)
+        {
+            //删除脚本   
+            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, @"([\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, @"&#(\d+);", "", RegexOptions.IgnoreCase);
+
+            Htmlstring.Replace("<", "");
+            Htmlstring.Replace(">", "");
+            Htmlstring.Replace("\r\n", "");
+
+            return Htmlstring;
+        }
+
+        #endregion
+
+        #region 4、匹配页面的链接
+        #region 4.1获取页面的链接正则
+        /// <summary>
+        /// 4.1获取页面的链接正则
+        /// </summary>
+        /// <param name="HtmlCode">html代码</param>
+        public static string GetHref(string HtmlCode)
+        {
+            string MatchVale = "";
+            string Reg = @"(h|H)(r|R)(e|E)(f|F) *= *('|"")?((\w|\\|\/|\.|:|-|_)+)[\S]*";
+            foreach (Match m in Regex.Matches(HtmlCode, Reg))
+            {
+                MatchVale += (m.Value).ToLower().Replace("href=", "").Trim() + "|";
+            }
+            return MatchVale;
+        }
+        #endregion
+
+        #region  4.2取得所有链接URL
+        /// <summary>
+        /// 4.2取得所有链接URL
+        /// </summary>
+        /// <param name="html"></param>
+        /// <returns></returns>
+        public static string GetAllURL(string html)
+        {
+            StringBuilder sb = new StringBuilder();
+            Match m = Regex.Match(html.ToLower(), "<a href=(.*?)>.*?</a>");
+
+            while (m.Success)
+            {
+                sb.AppendLine(m.Result("$1"));
+                m.NextMatch();
+            }
+
+            return sb.ToString();
+        }
+        #endregion
+
+        #region 4.3获取所有连接文本
+        /// <summary>
+        /// 4.3获取所有连接文本
+        /// </summary>
+        /// <param name="html"></param>
+        /// <returns></returns>
+        public static string GetAllLinkText(string html)
+        {
+            StringBuilder sb = new StringBuilder();
+            Match m = Regex.Match(html.ToLower(), "<a href=.*?>(1,100})</a>");
+
+            while (m.Success)
+            {
+                sb.AppendLine(m.Result("$1"));
+                m.NextMatch();
+            }
+
+            return sb.ToString();
+        }
+        #endregion
+        #endregion
+
+        #region  5、匹配页面的图片地址
+
+        /// <summary>
+        /// 5.1匹配页面的图片地址
+        /// </summary>
+        /// <param name="HtmlCode">html代码</param>
+        /// <param name="imgHttp">要补充的http://路径信息</param>
+        public static string GetImgSrc(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>
+        /// 5.2匹配<img src="" />中的图片路径实际链接
+        /// </summary>
+        /// <param name="ImgString"><img src="" />字符串</param>
+        /// <param name="imgHttp">图片路径</param>
+        public static string GetImg(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;
+            else
+                return imgHttp + MatchVale;
+        }
+        #endregion
+
+        #region 6、抓取远程页面内容
+        /// <summary>
+        /// 6.1以GET方式抓取远程页面内容
+        /// </summary>
+        /// <param name="tUrl">URL</param>
+        public static string Get_Http(string tUrl)
+        {
+            string strResult;
+            try
+            {
+                HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(tUrl);
+                hwr.Timeout = 19600;
+                HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
+                Stream myStream = hwrs.GetResponseStream();
+                StreamReader sr = new StreamReader(myStream, Encoding.Default);
+                StringBuilder sb = new StringBuilder();
+                while (-1 != sr.Peek())
+                {
+                    sb.Append(sr.ReadLine() + "\r\n");
+                }
+                strResult = sb.ToString();
+                hwrs.Close();
+            }
+            catch (Exception ee)
+            {
+                strResult = ee.Message;
+            }
+            return strResult;
+        }
+
+        /// <summary>
+        /// 6.2以POST方式抓取远程页面内容
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <param name="postData">参数列表</param>
+        /// <param name="encodeType">编码类型</param>
+        public static string Post_Http(string url, string postData, string encodeType)
+        {
+            string strResult = null;
+            try
+            {
+                Encoding encoding = Encoding.GetEncoding(encodeType);
+                byte[] POST = encoding.GetBytes(postData);
+                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
+                myRequest.Method = "POST";
+                myRequest.ContentType = "application/x-www-form-urlencoded";
+                myRequest.ContentLength = POST.Length;
+                Stream newStream = myRequest.GetRequestStream();
+                newStream.Write(POST, 0, POST.Length); //设置POST
+                newStream.Close();
+                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
+                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
+                strResult = reader.ReadToEnd();
+            }
+            catch (Exception ex)
+            {
+                strResult = ex.Message;
+            }
+            return strResult;
+        }
+        #endregion
+
+        #region 7、压缩HTML输出
+        /// <summary>
+        /// 7.1压缩HTML输出
+        /// </summary>
+        /// <param name="Html">html</param>
+        public static string ZipHtml(string 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>
+        /// 8.1过滤指定HTML标签
+        /// </summary>
+        /// <param name="s_TextStr">要过滤的字符</param>
+        /// <param name="html_Str">a img p div</param>
+        public static string DelHtml(string s_TextStr, string html_Str)
+        {
+            string rStr = "";
+            if (!string.IsNullOrEmpty(s_TextStr))
+            {
+                rStr = Regex.Replace(s_TextStr, "<" + html_Str + "[^>]*>", "", RegexOptions.IgnoreCase);
+                rStr = Regex.Replace(rStr, "</" + html_Str + ">", "", RegexOptions.IgnoreCase);
+            }
+            return rStr;
+        }
+        #endregion
+        #region 8.2过滤HTML中的不安全标签
+
+        /// <summary>
+        /// 8.2过滤HTML中的不安全标签
+        /// </summary>
+        /// <param name="content"></param>
+        /// <returns></returns>
+        public static string RemoveUnsafeHtml(string content)
+        {
+            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
+            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>
+        /// <param name="strHtml"></param>
+        /// <returns></returns>
+        public static string HtmlToTxt(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 newReg = aryReg[0];
+            string strOutput = strHtml;
+            for (int i = 0; i < aryReg.Length; i++)
+            {
+                Regex regex = new Regex(aryReg[i], 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>
+        /// <param name="str"></param>
+        /// <returns></returns>
+        public static string StringToHtml(string str)
+        {
+            str = str.Replace("&", "&amp;");
+            str = str.Replace(" ", "&nbsp;");
+            str = str.Replace("'", "''");
+            str = str.Replace("\"", "&quot;");
+            str = str.Replace("<", "&lt;");
+            str = str.Replace(">", "&gt;");
+            str = str.Replace("\n", "<br />");
+            str = str.Replace("\r", "<br />");
+            str = str.Replace("\r\n", "<br />");
+            return str;
+        }
+        #endregion
+
+        #region Html转换成字符串
+        /// <summary>
+        /// html转换成字符串
+        /// </summary>
+        /// <param name="strHtml"></param>
+        /// <returns></returns>
+        public static string HtmlToString(string strHtml)
+        {
+            strHtml = strHtml.Replace("<br>", "\r\n");
+            strHtml = strHtml.Replace(@"<br />", "\r\n");
+            strHtml = strHtml.Replace(@"<br/>", "\r\n");
+            strHtml = strHtml.Replace("&gt;", ">");
+            strHtml = strHtml.Replace("&lt;", "<");
+            strHtml = strHtml.Replace("&nbsp;", " ");
+            strHtml = strHtml.Replace("&quot;", "\"");
+            strHtml = Regex.Replace(strHtml, @"<\/?[^>]+>", "", RegexOptions.IgnoreCase);
+            return strHtml;
+        }
+        #endregion
+        #endregion
+
+        #region 获取URL编码
+        /// <summary>
+        /// 获取URL编码
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <returns></returns>
+        public static string GetEncoding(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) == true)
+                    {
+                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
+                    }
+                    else
+                    {
+                        reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
+                    }
+
+                    string html = reader.ReadToEnd();
+                    Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
+                    if (reg_charset.IsMatch(html))
+                    {
+                        return reg_charset.Match(html).Groups["charset"].Value;
+                    }
+                    else if (response.CharacterSet != string.Empty)
+                    {
+                        return response.CharacterSet;
+                    }
+                    else
+                    {
+                        return Encoding.Default.BodyName;
+                    }
+                }
+            }
+            catch
+            {
+            }
+            finally
+            {
+                if (response != null)
+                {
+                    response.Close();
+                    response = null;
+                }
+                if (reader != null)
+                    reader.Close();
+                if (request != null)
+                    request = null;
+            }
+            return Encoding.Default.BodyName;
+        }
+        #endregion
+
+        #region 判断URL是否有效
+
+        /// <summary>
+        /// 判断URL是否有效
+        /// </summary>
+        /// <param name="url">待判断的URL,可以是网页以及图片链接等</param>
+        /// <returns>200为正确,其余为大致网页错误代码</returns>
+        public static int GetUrlError(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)
+                {
+                    return 401;
+                }
+                if (exception.Message.IndexOf("404") > 0)
+                {
+                    num = 404;
+                }
+            }
+            catch
+            {
+                num = 401;
+            }
+            return num;
+        }
+        #endregion
+
+        #region 返回 HTML 字符串的编码解码结果
+        /// <summary>
+        /// 返回 HTML 字符串的编码结果
+        /// </summary>
+        /// <param name="inputData">字符串</param>
+        /// <returns>编码结果</returns>
+        public static string HtmlEncode(string inputData)
+        {
+            return HttpUtility.HtmlEncode(inputData);
+        }
+
+        /// <summary>
+        /// 返回 HTML 字符串的解码结果
+        /// </summary>
+        /// <param name="str">字符串</param>
+        /// <returns>解码结果</returns>
+        public static string HtmlDecode(string str)
+        {
+            return HttpUtility.HtmlDecode(str);
+        }
+        #endregion
+
+        #region 加载文件块
+        /// <summary>
+        /// 加载文件块
+        /// </summary>
+        /// <param name="Path">文件路径</param>
+        /// <param name="p">Page页</param>
+        public static string File(string Path, System.Web.UI.Page p)
+        {
+            return @p.ResolveUrl(Path);
+        }
+        #endregion
+
+        #region 加载CSS样式文件
+        /// <summary>
+        /// 加载CSS样式文件
+        /// </summary>
+        /// <param name="cssPath">css路径</param>
+        /// <param name="p">Page页</param>
+        public static string CSS(string cssPath, System.Web.UI.Page p)
+        {
+            return @"<link href=""" + p.ResolveUrl(cssPath) + @""" rel=""stylesheet"" type=""text/css"" />" + "\r\n";
+        }
+        #endregion
+
+        #region 加载JavaScript脚本文件
+        /// <summary>
+        /// 加载javascript脚本文件
+        /// </summary>
+        /// <param name="jsPath">js路径</param>
+        /// <param name="p">web页面</param>
+        public static string Javascript(string jsPath, System.Web.UI.Page p)
+        {
+            return @"<script type=""text/javascript"" src=""" + p.ResolveUrl(jsPath) + @"""></script>" + "\r\n";
+        }
+        #endregion
+
+        /// <summary>
+        /// 获取Cookie集合
+        /// </summary>
+        /// <param name="cookieString">Cookie的键</param>
+        /// <returns>Cookie键值集合</returns>
+        public static CookieCollection GetCookieCollection(string cookieString)
+        {
+            CookieCollection ccc = new CookieCollection();
+            //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))
+            {
+                //name,   value,   path,   domain   
+                Cookie c = new Cookie(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value, m.Groups[3].Value);
+                ccc.Add(c);
+            }
+            return ccc;
+        }
+
+        #region 从HTML中获取文本,保留br,p,img
+
+        /// <summary>
+        /// 从HTML中获取文本,保留br,p,img
+        /// </summary>
+        /// <param name="HTML"></param>
+        /// <returns></returns>
+        public static string GetTextFromHTML(string HTML)
+        {
+            Regex regEx = new Regex(@"</?(?!br|/?p|img)[^>]*>", RegexOptions.IgnoreCase);
+
+            return regEx.Replace(HTML, "");
+        }
+        #endregion
+
+        #region 获取HTML页面内制定Key的Value内容
+
+        /// <summary>
+        /// 获取HTML页面内制定Key的Value内容
+        /// </summary>
+        /// <param name="html"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static string GetHiddenKeyValue(string html, string key)
+        {
+            string result = "";
+            string sRegex = string.Format("<input\\s*type=\"hidden\".*?name=\"{0}\".*?\\s*value=[\"|'](?<value>.*?)[\"|'^/]", key);
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match mc = re.Match(html);
+            if (mc.Success)
+            {
+                result = mc.Groups[1].Value;
+            }
+            return result;
+        }
+        #endregion
+
+        /// <summary>
+        /// 替换回车换行符为html换行符
+        /// </summary>
+        /// <param name="str">html</param>
+        public static string StrFormat(string str)
+        {
+            string str2;
+            if (str == null)
+            {
+                str2 = "";
+            }
+            else
+            {
+                str = str.Replace("\r\n", "<br />");
+                str = str.Replace("\n", "<br />");
+                str2 = str;
+            }
+            return str2;
+        }
+        /// <summary>
+        /// 替换html字符
+        /// </summary>
+        /// <param name="strHtml">html</param>
+        public static string EncodeHtml(string strHtml)
+        {
+            if (strHtml != "")
+            {
+                strHtml = strHtml.Replace(",", "&def");
+                strHtml = strHtml.Replace("'", "&dot");
+                strHtml = strHtml.Replace(";", "&dec");
+                return strHtml;
+            }
+            return "";
+        }
+
+        /// <summary>
+        /// 为脚本替换特殊字符串
+        /// </summary>
+        /// <param name="str"></param>
+        /// <returns></returns>
+        public static string ReplaceStrToScript(string str)
+        {
+            str = str.Replace("\\", "\\\\");
+            str = str.Replace("'", "\\'");
+            str = str.Replace("\"", "\\\"");
+            return str;
+        }
+    }
+}

+ 432 - 0
Masuit.Tools/Html/HtmlPager.cs

@@ -0,0 +1,432 @@
+using System;
+using System.Text;
+
+namespace Masuit.Tools.Html
+{
+    /// <summary>
+    /// HTMl 分页
+    /// </summary>
+    public static class HtmlPager
+    {
+        /// <summary>
+        /// 写出分页
+        /// </summary>
+        /// <param name="pageCount">页数</param>
+        /// <param name="currentPage">当前页</param>
+        public static string GetPager(int pageCount, int currentPage)
+        {
+            return GetPager(pageCount, currentPage, new string[] { }, new string[] { });
+        }
+
+        /// <summary>
+        /// 写出分页
+        /// </summary>
+        /// <param name="pageCount">页数</param>
+        /// <param name="currentPage">当前页</param>
+        /// <param name="FieldName">地址栏参数</param>
+        /// <param name="FieldValue">地址栏参数值</param>
+        /// <returns></returns>
+        public static string GetPager(int pageCount, int currentPage, string[] FieldName, string[] FieldValue)
+        {
+            string pString = "";
+            for (int i = 0; i < FieldName.Length; i++)
+            {
+                pString += "&" + FieldName[i] + "=" + FieldValue[i];
+            }
+            int stepNum = 4;
+            int pageRoot = 1;
+            pageCount = pageCount == 0 ? 1 : pageCount;
+            currentPage = currentPage == 0 ? 1 : currentPage;
+
+            StringBuilder sb = new StringBuilder();
+            sb.Append("<table cellpadding=0 cellspacing=1 class=\"pager\">\r<tr>\r");
+            sb.Append("<td class=pagerTitle>&nbsp;分页&nbsp;</td>\r");
+            sb.Append("<td class=pagerTitle>&nbsp;" + currentPage + "/" + pageCount + "&nbsp;</td>\r");
+            if (currentPage - stepNum < 2)
+                pageRoot = 1;
+            else
+                pageRoot = currentPage - stepNum;
+            int pageFoot = pageCount;
+            if (currentPage + stepNum >= pageCount)
+                pageFoot = pageCount;
+            else
+                pageFoot = currentPage + stepNum;
+            if (pageRoot == 1)
+            {
+                if (currentPage > 1)
+                {
+                    sb.Append("<td>&nbsp;<a href='?page=1" + pString + "' title='首页'>首页</a>&nbsp;</td>\r");
+                    sb.Append("<td>&nbsp;<a href='?page=" + Convert.ToString(currentPage - 1) + pString + "' title='上页'>上页</a>&nbsp;</td>\r");
+                }
+            }
+            else
+            {
+                sb.Append("<td>&nbsp;<a href='?page=1" + pString + "' title='首页'>首页</a>&nbsp;</td>");
+                sb.Append("<td>&nbsp;<a href='?page=" + Convert.ToString(currentPage - 1) + pString + "' title='上页'>上页</a>&nbsp;</td>\r");
+            }
+            for (int i = pageRoot; i <= pageFoot; i++)
+            {
+                if (i == currentPage)
+                {
+                    sb.Append("<td class='current'>&nbsp;" + i.ToString() + "&nbsp;</td>\r");
+                }
+                else
+                {
+                    sb.Append("<td>&nbsp;<a href='?page=" + i.ToString() + pString + "' title='第" + i.ToString() + "页'>" + i.ToString() + "</a>&nbsp;</td>\r");
+                }
+                if (i == pageCount)
+                    break;
+            }
+            if (pageFoot == pageCount)
+            {
+                if (pageCount > currentPage)
+                {
+                    sb.Append("<td>&nbsp;<a href='?page=" + Convert.ToString(currentPage + 1) + pString + "' title='下页'>下页</a>&nbsp;</td>\r");
+                    sb.Append("<td>&nbsp;<a href='?page=" + pageCount.ToString() + pString + "' title='尾页'>尾页</a>&nbsp;</td>\r");
+                }
+            }
+            else
+            {
+                sb.Append("<td>&nbsp;<a href='?page=" + Convert.ToString(currentPage + 1) + pString + "' title='下页'>下页</a>&nbsp;</td>\r");
+                sb.Append("<td>&nbsp;<a href='?page=" + pageCount.ToString() + pString + "' title='尾页'>尾页</a>&nbsp;</td>\r");
+            }
+            sb.Append("</tr>\r</table>");
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 写出分页
+        /// </summary>
+        /// <param name="pageCount">总页数</param>
+        /// <param name="currentPage">当前页</param>
+        /// <param name="prefix">上一页</param>
+        /// <param name="suffix">下一页</param>
+        /// <returns></returns>
+        public static string GetHtmlPager(int pageCount, int currentPage, string prefix, string suffix)
+        {
+            int stepNum = 4;
+            int pageRoot = 1;
+            pageCount = pageCount == 0 ? 1 : pageCount;
+            currentPage = currentPage == 0 ? 1 : currentPage;
+            StringBuilder sb = new StringBuilder();
+            sb.Append("<table cellpadding=0 cellspacing=1 class=\"pager\">\r<tr>\r");
+            sb.Append("<td class=pagerTitle>&nbsp;分页&nbsp;</td>\r");
+            sb.Append("<td class=pagerTitle>&nbsp;" + currentPage.ToString() + "/" + pageCount.ToString() + "&nbsp;</td>\r");
+            if (currentPage - stepNum < 2)
+                pageRoot = 1;
+            else
+                pageRoot = currentPage - stepNum;
+            int pageFoot = pageCount;
+            if (currentPage + stepNum >= pageCount)
+                pageFoot = pageCount;
+            else
+                pageFoot = currentPage + stepNum;
+            if (pageRoot == 1)
+            {
+                if (currentPage > 1)
+                {
+                    sb.Append("<td>&nbsp;<a href='" + prefix + "1" + suffix + "' title='首页'>首页</a>&nbsp;</td>\r");
+                    sb.Append("<td>&nbsp;<a href='" + prefix + Convert.ToString(currentPage - 1) + suffix + "' title='上页'>上页</a>&nbsp;</td>\r");
+                }
+            }
+            else
+            {
+                sb.Append("<td>&nbsp;<a href='" + prefix + "1" + suffix + "' title='首页'>首页</a>&nbsp;</td>");
+                sb.Append("<td>&nbsp;<a href='" + prefix + Convert.ToString(currentPage - 1) + suffix + "' title='上页'>上页</a>&nbsp;</td>\r");
+            }
+            for (int i = pageRoot; i <= pageFoot; i++)
+            {
+                if (i == currentPage)
+                {
+                    sb.Append("<td class='current'>&nbsp;" + i.ToString() + "&nbsp;</td>\r");
+                }
+                else
+                {
+                    sb.Append("<td>&nbsp;<a href='" + prefix + i.ToString() + suffix + "' title='第" + i.ToString() + "页'>" + i.ToString() + "</a>&nbsp;</td>\r");
+                }
+                if (i == pageCount)
+                    break;
+            }
+            if (pageFoot == pageCount)
+            {
+                if (pageCount > currentPage)
+                {
+                    sb.Append("<td>&nbsp;<a href='" + prefix + Convert.ToString(currentPage + 1) + suffix + "' title='下页'>下页</a>&nbsp;</td>\r");
+                    sb.Append("<td>&nbsp;<a href='" + prefix + pageCount.ToString() + suffix + "' title='尾页'>尾页</a>&nbsp;</td>\r");
+                }
+            }
+            else
+            {
+                sb.Append("<td>&nbsp;<a href='" + prefix + Convert.ToString(currentPage + 1) + suffix + "' title='下页'>下页</a>&nbsp;</td>\r");
+                sb.Append("<td>&nbsp;<a href='" + prefix + pageCount.ToString() + suffix + "' title='尾页'>尾页</a>&nbsp;</td>\r");
+            }
+            sb.Append("</tr>\r</table>");
+            return sb.ToString();
+        }
+
+        #region 分页
+
+        /// <summary>
+        /// 分页
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <param name="para">参数</param>
+        /// <param name="sumpage">总页数</param>
+        /// <param name="page">当前页</param>
+        /// <returns>当前页的内容</returns>
+        public static string Paging(string url, string para, int sumpage, int page)
+        {
+            string result = string.Empty;
+            if (sumpage == 1)
+            {
+                return result;
+            }
+            if (sumpage > 500)
+            {
+                sumpage = 500;
+            }
+            if (page > sumpage)
+            {
+                page = 1;
+            }
+            StringBuilder sb = new StringBuilder();
+            if (sumpage > 0)
+            {
+                switch (page)
+                {
+                    case 1:
+                        sb.Append(string.Format("<p class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a> ", new object[] { url, page + 1, para, "下一页" }));
+                        break;
+                    default:
+                        if (sumpage == page)
+                        {
+                            sb.Append(string.Format("<p class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a> ", new object[] { url, page - 1, para, "上一页" }));
+                        }
+                        else
+                        {
+                            sb.Append(string.Format("<p class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a> <a href=\"{4}?page={5}{6}\">{7}</a> ",
+                                new object[] { url, page + 1, para, "下一页", url, page - 1, para, "上一页" }));
+                        }
+                        break;
+                }
+                sb.Append(string.Format("第{0}/{1}页</p>", new object[] { page, sumpage }));
+            }
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 分页控件
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <param name="para">参数</param>
+        /// <param name="sumpage">总页数</param>
+        /// <param name="page">当前页</param>
+        /// <param name="myPaging">分页控件</param>
+        /// <returns>当前页的内容</returns>
+        public static string Paging(string url, string para, int sumpage, int page, System.Web.UI.UserControl myPaging)
+        {
+            myPaging.Visible = false;
+            string result = string.Empty;
+            if (sumpage == 1)
+            {
+                return result;
+            }
+            if (sumpage > 500)
+            {
+                sumpage = 500;
+            }
+            if (page > sumpage)
+            {
+                page = 1;
+            }
+            StringBuilder sb = new StringBuilder();
+            if (sumpage > 0)
+            {
+                myPaging.Visible = true;
+                switch (page)
+                {
+                    case 1:
+                        sb.Append(string.Format("<a href=\"{0}?page={1}{2}\">{3}</a> ", new object[] { url, page + 1, para, "下一页" }));
+                        break;
+                    default:
+                        if (sumpage == page)
+                        {
+                            sb.Append(string.Format("<a href=\"{0}?page={1}{2}\">{3}</a> ", new object[] { url, page - 1, para, "上一页" }));
+                        }
+                        else
+                        {
+                            sb.Append(string.Format("<a href=\"{0}?page={1}{2}\">{3}</a> <a href=\"{4}?page={5}{6}\">{7}</a> ",
+                                new object[] { url, page + 1, para, "下一页", url, page - 1, para, "上一页" }));
+                        }
+                        break;
+                }
+                sb.Append(string.Format("第{0}/{1}页", new object[] { page, sumpage }));
+            }
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 分页
+        /// </summary>
+        /// <param name="para">参数</param>
+        /// <param name="sumpage">总页数</param>
+        /// <param name="page">当前页</param>
+        /// <param name="count">总条数</param>
+        /// <returns>当前页的内容</returns>
+        public static string Paging(string para, int sumpage, int page, int count)
+        {
+            string result = string.Empty;
+            if (page > sumpage)
+            {
+                page = 1;
+            }
+            StringBuilder sb = new StringBuilder();
+            if (sumpage > 0)
+            {
+                if (sumpage != 1)
+                {
+                    switch (page)
+                    {
+                        case 1:
+                            sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a> ", new object[] { page + 1, para, "下一页" }));
+                            break;
+                        default:
+                            if (sumpage == page)
+                            {
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a> ", new object[] { page - 1, para, "上一页" }));
+                            }
+                            else
+                            {
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a> <a href=\"?page={3}{4}\">{5}</a> ",
+                                    new object[] { page - 1, para, "上一页", page + 1, para, "下一页" }));
+                            }
+                            break;
+                    }
+                }
+                sb.Append(string.Format("第{0}/{1}页 共{2}条", new object[] { page, sumpage, count }));
+            }
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 带第一页和最后一页
+        /// </summary>
+        /// <param name="para">参数</param>
+        /// <param name="sumpage">总页数</param>
+        /// <param name="page">当前页</param>
+        /// <param name="count">总条数</param>
+        /// <returns>当前页的内容</returns>
+        public static string paging2(string para, int sumpage, int page, int count)
+        {
+            string result = string.Empty;
+            if (page > sumpage)
+            {
+                page = 1;
+            }
+            StringBuilder sb = new StringBuilder();
+            if (sumpage > 0)
+            {
+                if (sumpage != 1)
+                {
+                    //第一页
+                    sb.Append(string.Format("<a href=\"?page={0}{1}\"><img src=\"images/first-icon.gif\" border=\"0\"/></a>&nbsp;&nbsp;", new object[] { 1, para }));
+                    switch (page)
+                    {
+                        case 1:
+                            //前一页图片
+                            sb.Append(string.Format("<a>{0}</a>", new object[] { "<img src=\"images/left-icon.gif\" border=\"0\"/>" }));
+                            sb.Append(string.Format("<a>上一页</a><a href=\"?page={0}{1}\">{2}</a> ", new object[] { page + 1, para, "下一页" }));
+                            //后一页图片
+                            sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page + 1, para, "<img src=\"images/right-icon.gif\" border=\"0\"/>" }));
+                            break;
+                        default:
+                            if (sumpage == page)
+                            {
+                                //前一页图片
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page - 1, para, "<img src=\"images/left-icon.gif\" border=\"0\"/>" }));
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a><a>下一页</a> ", new object[] { page - 1, para, "上一页" }));
+                                //后一页图片
+                                sb.Append(string.Format("<a>{0}</a>", new object[] { "<img src=\"images/right-icon.gif\" />" }));
+                            }
+                            else
+                            {
+                                //前一页图片
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page - 1, para, "<img src=\"images/left-icon.gif\" border=\"0\"/>" }));
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a> <a href=\"?page={3}{4}\">{5}</a> ",
+                                    new object[] { page - 1, para, "上一页", page + 1, para, "下一页" }));
+                                //后一页图片
+                                sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page + 1, para, "<img src=\"images/right-icon.gif\" border=\"0\"/>" }));
+                            }
+                            break;
+                    }
+                    //最后一页图片
+                    sb.Append(string.Format("&nbsp;&nbsp;<a href=\"?page={0}{1}\"><img src=\"images/last-icon.gif\" border=\"0\"/></a>&nbsp;&nbsp;", new object[] { sumpage, para }));
+                }
+                sb.Append(string.Format("第{0}页/共{1}页 共{2}条", new object[] { page, sumpage, count }));
+            }
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 分页
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <param name="para">参数</param>
+        /// <param name="sumpage">总页数</param>
+        /// <param name="page">当前页</param>
+        /// <param name="count">总条数</param>
+        /// <returns>当前页的内容</returns>
+        public static string Paging(string url, string para, int sumpage, int page, int count)
+        {
+            string result = string.Empty;
+            if (page > sumpage)
+            {
+                page = 1;
+            }
+            StringBuilder sb = new StringBuilder();
+            if (sumpage > 0)
+            {
+                if (sumpage != 1)
+                {
+                    //第一页
+                    sb.Append(string.Format("<a href=\"{2}?page={0}{1}\">首页</a>", new object[] { 1, para, url }));
+                    switch (page)
+                    {
+                        case 1:
+                            //前一页图片
+                            // sb.Append(string.Format("<a>{0}</a>", new object[] { "<img src=\"images/left-icon.gif\" border=\"0\"/>" }));
+                            sb.Append(string.Format("<a>上一页</a><a href=\"{3}?page={0}{1}\">{2}</a> ", new object[] { page + 1, para, "下一页", url }));
+                            //后一页图片
+                            // sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page + 1, para, "<img src=\"images/right-icon.gif\" border=\"0\"/>" }));
+                            break;
+                        default:
+                            if (sumpage == page)
+                            {
+                                //前一页图片
+                                //sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page - 1, para, "<img src=\"images/left-icon.gif\" border=\"0\"/>" }));
+                                sb.Append(string.Format("<a href=\"{3}?page={0}{1}\">{2}</a><a>下一页</a> ", new object[] { page - 1, para, "上一页", url }));
+                                //后一页图片
+                                //sb.Append(string.Format("<a>{0}</a>", new object[] { "<img src=\"images/right-icon.gif\" />" }));
+                            }
+                            else
+                            {
+                                //前一页图片
+                                //sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page - 1, para, "<img src=\"images/left-icon.gif\" border=\"0\"/>" }));
+                                sb.Append(string.Format("<a href=\"{6}?page={0}{1}\">{2}</a> <a href=\"{6}?page={3}{4}\">{5}</a> ",
+                                    new object[] { page - 1, para, "上一页", page + 1, para, "下一页", url }));
+                                //后一页图片
+                                //sb.Append(string.Format("<a href=\"?page={0}{1}\">{2}</a>", new object[] { page + 1, para, "<img src=\"images/right-icon.gif\" border=\"0\"/>" }));
+                            }
+                            break;
+                    }
+                    //最后一页图片
+                    sb.Append(string.Format("<a href=\"{2}?page={0}{1}\">末页</a>&nbsp;&nbsp;", new object[] { sumpage, para, url }));
+                }
+                sb.Append(string.Format("第{0}页/共{1}页 共{2}条", new object[] { page, sumpage, count }));
+            }
+            return sb.ToString();
+        }
+        #endregion
+
+    }
+}

+ 53 - 0
Masuit.Tools/Html/HtmlTools.cs

@@ -0,0 +1,53 @@
+using System;
+using System.Text.RegularExpressions;
+
+namespace Masuit.Tools.Html
+{
+    /// <summary>
+    /// HTML工具类
+    /// </summary>
+    public static class HtmlTools
+    {
+        #region 获得发表日期、编码
+        /// <summary>
+        /// 获得发表日期、编码
+        /// </summary>
+        /// <param name="sContent">内容</param>
+        /// <param name="sRegex">正则表达式</param>
+        /// <returns>日期</returns>
+        public static DateTime GetCreateDate(string sContent, string sRegex)
+        {
+            DateTime dt = System.DateTime.Now;
+
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match mc = re.Match(sContent);
+            if (mc.Success)
+            {
+                try
+                {
+                    int iYear = int.Parse(mc.Groups["Year"].Value);
+                    int iMonth = int.Parse(mc.Groups["Month"].Value);
+                    int iDay = int.Parse(mc.Groups["Day"].Value);
+                    int iHour = dt.Hour;
+                    int iMinute = dt.Minute;
+
+                    string sHour = mc.Groups["Hour"].Value;
+                    string sMintue = mc.Groups["Mintue"].Value;
+
+                    if (sHour != "")
+                        iHour = int.Parse(sHour);
+                    if (sMintue != "")
+                        iMinute = int.Parse(sMintue);
+
+                    dt = new DateTime(iYear, iMonth, iDay, iHour, iMinute, 0);
+                }
+                catch
+                {
+                }
+            }
+            return dt;
+        }
+        #endregion 获得发表日期
+
+    }
+}

+ 1573 - 0
Masuit.Tools/Html/HtmlUtils.cs

@@ -0,0 +1,1573 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Data;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Web;
+using System.Xml;
+
+namespace Masuit.Tools.Html
+{
+    /// <summary>
+    /// html工具类
+    /// </summary>
+    public static class HtmlUtils
+    {
+        #region BaseMethod
+        /// <summary>
+        /// 多个匹配内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="iGroupIndex">第几个分组, 从1开始, 0代表不分组</param>
+        public static List<string> GetList(string sInput, string sRegex, int iGroupIndex)
+        {
+            List<string> list = new List<string>();
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sInput);
+            foreach (Match mc in mcs)
+            {
+                if (iGroupIndex > 0)
+                {
+                    list.Add(mc.Groups[iGroupIndex].Value);
+                }
+                else
+                {
+                    list.Add(mc.Value);
+                }
+            }
+            return list;
+        }
+
+        /// <summary>
+        /// 多个匹配内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="sGroupName">分组名, ""代表不分组</param>
+        public static List<string> GetList(string sInput, string sRegex, string sGroupName)
+        {
+            List<string> list = new List<string>();
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sInput);
+            foreach (Match mc in mcs)
+            {
+                if (sGroupName != "")
+                {
+                    list.Add(mc.Groups[sGroupName].Value);
+                }
+                else
+                {
+                    list.Add(mc.Value);
+                }
+            }
+            return list;
+        }
+
+        /// <summary>
+        /// 单个匹配内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="iGroupIndex">分组序号, 从1开始, 0不分组</param>
+        public static string GetText(string sInput, string sRegex, int iGroupIndex)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match mc = re.Match(sInput);
+            string result = "";
+            if (mc.Success)
+            {
+                if (iGroupIndex > 0)
+                {
+                    result = mc.Groups[iGroupIndex].Value;
+                }
+                else
+                {
+                    result = mc.Value;
+                }
+            }
+            return result;
+        }
+
+        /// <summary>
+        /// 单个匹配内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="sGroupName">分组名, ""代表不分组</param>
+        public static string GetText(string sInput, string sRegex, string sGroupName)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match mc = re.Match(sInput);
+            string result = "";
+            if (mc.Success)
+            {
+                if (sGroupName != "")
+                {
+                    result = mc.Groups[sGroupName].Value;
+                }
+                else
+                {
+                    result = mc.Value;
+                }
+            }
+            return result;
+        }
+
+        /// <summary>
+        /// 替换指定内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="sReplace">替换值</param>
+        /// <param name="iGroupIndex">分组序号, 0代表不分组</param>
+        public static string Replace(string sInput, string sRegex, string sReplace, int iGroupIndex)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sInput);
+            foreach (Match mc in mcs)
+            {
+                if (iGroupIndex > 0)
+                {
+                    sInput = sInput.Replace(mc.Groups[iGroupIndex].Value, sReplace);
+                }
+                else
+                {
+                    sInput = sInput.Replace(mc.Value, sReplace);
+                }
+            }
+            return sInput;
+        }
+
+        /// <summary>
+        /// 替换指定内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="sReplace">替换值</param>
+        /// <param name="sGroupName">分组名, "" 代表不分组</param>
+        public static string Replace(string sInput, string sRegex, string sReplace, string sGroupName)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sInput);
+            foreach (Match mc in mcs)
+            {
+                if (sGroupName != "")
+                {
+                    sInput = sInput.Replace(mc.Groups[sGroupName].Value, sReplace);
+                }
+                else
+                {
+                    sInput = sInput.Replace(mc.Value, sReplace);
+                }
+            }
+            return sInput;
+        }
+
+        /// <summary>
+        /// 分割指定内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        /// <param name="iStrLen">最小保留字符串长度</param>
+        public static List<string> Split(string sInput, string sRegex, int iStrLen)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            string[] sArray = re.Split(sInput);
+            List<string> list = new List<string>();
+            list.Clear();
+            foreach (string s in sArray)
+            {
+                if (s.Trim().Length < iStrLen)
+                    continue;
+
+                list.Add(s.Trim());
+            }
+            return list;
+        }
+
+        #endregion BaseMethod
+
+        #region 获得特定内容
+
+        /// <summary>
+        /// 多个链接
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static List<string> GetLinks(string sInput)
+        {
+            return GetList(sInput, @"<a[^>]+href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>", "href");
+        }
+
+        /// <summary>
+        /// 单个链接
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static string GetLinkHelp(string sInput)
+        {
+            return GetText(sInput, @"<a[^>]+href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>", "href");
+        }
+
+        /// <summary>
+        /// 图片标签
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static List<string> GetImgTag(string sInput)
+        {
+            return GetList(sInput, "<img[^>]+src=\\s*(?:'(?<src>[^']+)'|\"(?<src>[^\"]+)\"|(?<src>[^>\\s]+))\\s*[^>]*>", "");
+        }
+
+        /// <summary>
+        /// 图片地址
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static string GetImgSrc(string sInput)
+        {
+            return GetText(sInput, "<img[^>]+src=\\s*(?:'(?<src>[^']+)'|\"(?<src>[^\"]+)\"|(?<src>[^>\\s]+))\\s*[^>]*>", "src");
+        }
+
+        /// <summary>
+        /// 根据URL获得域名
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static string GetDomain(string sInput)
+        {
+            return GetText(sInput, @"http(s)?://([\w-]+\.)+(\w){2,}", 0);
+        }
+
+        #endregion 获得特定内容
+
+        #region 根据表达式,获得文章内容
+        /// <summary>
+        /// 文章标题
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        public static string GetTitle(string sInput, string sRegex)
+        {
+            string sTitle = GetText(sInput, sRegex, "Title");
+            sTitle = ClearTag(sTitle);
+            if (sTitle.Length > 99)
+            {
+                sTitle = sTitle.Substring(0, 99);
+            }
+            return sTitle;
+        }
+
+        /// <summary>
+        /// 网页标题
+        /// </summary>
+        /// <param name="sInput">html</param>
+        public static string GetTitle(string sInput)
+        {
+            return GetText(sInput, @"<Title[^>]*>(?<Title>[\s\S]{10,})</Title>", "Title");
+        }
+
+        /// <summary>
+        /// 网页内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static string GetHtml(string sInput)
+        {
+            return Replace(sInput, @"(?<Head>[^<]+)<", "", "Head");
+        }
+
+        /// <summary>
+        /// 网页Body内容
+        /// </summary>
+        /// <param name="sInput">html</param>
+        public static string GetBodyHelp(string sInput)
+        {
+            return GetText(sInput, @"<Body[^>]*>(?<Body>[\s\S]{10,})</body>", "Body");
+        }
+
+        /// <summary>
+        /// 网页Body内容
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        public static string GetBody(string sInput, string sRegex)
+        {
+            return GetText(sInput, sRegex, "Body");
+        }
+
+        /// <summary>
+        /// 文章来源
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        public static string GetSource(string sInput, string sRegex)
+        {
+            string sSource = GetText(sInput, sRegex, "Source");
+            sSource = ClearTag(sSource);
+            if (sSource.Length > 99)
+                sSource = sSource.Substring(0, 99);
+            return sSource;
+        }
+
+        /// <summary>
+        /// 作者名
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        public static string GetAuthor(string sInput, string sRegex)
+        {
+            string sAuthor = GetText(sInput, sRegex, "Author");
+            sAuthor = ClearTag(sAuthor);
+            if (sAuthor.Length > 99)
+                sAuthor = sAuthor.Substring(0, 99);
+            return sAuthor;
+        }
+
+        /// <summary>
+        /// 分页链接地址
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        /// <param name="sRegex">表达式字符串</param>
+        public static List<string> GetPageLinks(string sInput, string sRegex)
+        {
+            return GetList(sInput, sRegex, "href");
+        }
+
+        /// <summary>
+        /// 根据相对路径得到绝对路径
+        /// </summary>
+        /// <param name="sInput">原始网站地址</param>
+        /// <param name="sRelativeUrl">相对链接地址</param>
+        public static string GetUrl(string sInput, string sRelativeUrl)
+        {
+            string sReturnUrl = "";
+            string sUrl = _GetStandardUrlDepth(sInput);//返回了http://www.163.com/news/这种形式
+
+            if (sRelativeUrl.ToLower().StartsWith("http") || sRelativeUrl.ToLower().StartsWith("https"))
+            {
+                sReturnUrl = sRelativeUrl.Trim();
+            }
+            else if (sRelativeUrl.StartsWith("/"))
+            {
+                sReturnUrl = GetDomain(sInput) + sRelativeUrl;
+            }
+            else if (sRelativeUrl.StartsWith("../"))
+            {
+                sUrl = sUrl.Substring(0, sUrl.Length - 1);
+                while (sRelativeUrl.IndexOf("../") >= 0)
+                {
+                    string temp = sUrl.Substring(0, sUrl.LastIndexOf("/")); // CString.GetPreStrByLast(sUrl, "/");
+                    if (temp.Length > 6)
+                    {//temp != "http:/",否则的话,说明已经回溯到尽头了,"../"与网址的层次对应不上。存在这种情况,网页上面的链接是错误的,但浏览器还能正常显示
+                        sUrl = temp;
+                    }
+                    sRelativeUrl = sRelativeUrl.Substring(3);
+                }
+                sReturnUrl = sUrl + "/" + sRelativeUrl.Trim();
+            }
+            else if (sRelativeUrl.StartsWith("./"))
+            {
+                sReturnUrl = sUrl + sRelativeUrl.Trim().Substring(2);
+            }
+            else if (sRelativeUrl.Trim() != "")
+            {//2007images/modecss.css
+                sReturnUrl = sUrl + sRelativeUrl.Trim();
+            }
+            else
+            {
+                sRelativeUrl = sUrl;
+            }
+            return sReturnUrl;
+        }
+
+        /// <summary>
+        /// 获得标准的URL路径深度
+        /// </summary>
+        /// <param name="url"></param>
+        /// <returns>返回标准的形式:http://www.163.com/或http://www.163.com/news/。</returns>
+        private static string _GetStandardUrlDepth(string url)
+        {
+            string sheep = url.Trim().ToLower();
+            string header = "http://";
+            if (sheep.IndexOf("https://") != -1)
+            {
+                header = "https://";
+                sheep = sheep.Replace("https://", "");
+            }
+            else
+            {
+                sheep = sheep.Replace("http://", "");
+            }
+
+            int p = sheep.LastIndexOf("/");
+            if (p == -1)
+            {//www.163.com
+                sheep += "/";
+            }
+            else if (p == sheep.Length - 1)
+            {//传来的是:http://www.163.com/news/
+            }
+            else if (sheep.Substring(p).IndexOf(".") != -1)
+            {//传来的是:http://www.163.com/news/hello.htm 这种形式
+                sheep = sheep.Substring(0, p + 1);
+            }
+            else
+            {
+                sheep += "/";
+            }
+
+            return header + sheep;
+        }
+
+        /// <summary>
+        /// 关键字
+        /// </summary>
+        /// <param name="sInput">输入内容</param>
+        public static string GetKeyWord(string sInput)
+        {
+            List<string> list = Split(sInput, "(,|,|\\+|+|。|;|;|:|:|“)|”|、|_|\\(|(|\\)|)", 2);
+            List<string> listReturn = new List<string>();
+            Regex re;
+            foreach (string str in list)
+            {
+                re = new Regex(@"[a-zA-z]+", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
+                MatchCollection mcs = re.Matches(str);
+                string sTemp = str;
+                foreach (Match mc in mcs)
+                {
+                    if (mc.Value.Length > 2)
+                        listReturn.Add(mc.Value);
+                    sTemp = sTemp.Replace(mc.Value, ",");
+                }
+                re = new Regex(@",{1}", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
+                mcs = re.Matches(sTemp);
+                foreach (string s in re.Split(sTemp))
+                {
+                    if (s.Trim().Length <= 2)
+                        continue;
+                    listReturn.Add(s);
+                }
+            }
+            string sReturn = "";
+            for (int i = 0; i < listReturn.Count - 1; i++)
+            {
+                for (int j = i + 1; j < listReturn.Count; j++)
+                {
+                    if (listReturn[i] == listReturn[j])
+                    {
+                        listReturn[j] = "";
+                    }
+                }
+            }
+            foreach (string str in listReturn)
+            {
+                if (str.Length > 2)
+                    sReturn += str + ",";
+            }
+            if (sReturn.Length > 0)
+                sReturn = sReturn.Substring(0, sReturn.Length - 1);
+            else
+                sReturn = sInput;
+            if (sReturn.Length > 99)
+                sReturn = sReturn.Substring(0, 99);
+            return sReturn;
+        }
+
+        /// <summary>
+        /// 获取内容
+        /// </summary>
+        /// <param name="sOriContent">原始数据</param>
+        /// <param name="sOtherRemoveReg">需要移除的字符</param>
+        /// <param name="sPageUrl">URL</param>
+        /// <param name="dtAntiLink">反链 表数据</param>
+        /// <returns>转码后的内容</returns>
+        public static string GetContent(string sOriContent, string sOtherRemoveReg, string sPageUrl, DataTable dtAntiLink)
+        {
+            string sFormartted = sOriContent;
+
+            //去掉有危险的标记
+            sFormartted = Regex.Replace(sFormartted, @"<script[\s\S]*?</script>", "", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
+            sFormartted = Regex.Replace(sFormartted, @"<iframe[^>]*>[\s\S]*?</iframe>", "", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
+            Regex r = new Regex(@"<input[\s\S]+?>|<form[\s\S]+?>|</form[\s\S]*?>|<select[\s\S]+?>?</select>|<textarea[\s\S]*?>?</textarea>|<file[\s\S]*?>|<noscript>|</noscript>", RegexOptions.IgnoreCase);
+            sFormartted = r.Replace(sFormartted, "");
+            string[] sOtherReg = sOtherRemoveReg.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
+            foreach (string sRemoveReg in sOtherReg)
+            {
+                sFormartted = Replace(sFormartted, sRemoveReg, "", 0);
+            }
+
+            //图片路径
+            //sFormartted = _ReplaceUrl("<img[^>]+src\\s*=\\s*(?:'(?<src>[^']+)'|\"(?<src>[^\"]+)\"|(?<src>[^>\\s]+))\\s*[^>]*>", "src", sFormartted,sPageUrl);
+            sFormartted = _ReplaceUrl("<img[\\s\\S]+?src\\s*=\\s*(?:'(?<src>[^']+)'|\"(?<src>[^\"]+)\"|(?<src>[^>\\s]+))\\s*[^>]*>", "src", sFormartted, sPageUrl);
+            //反防盗链
+            string domain = GetDomain(sPageUrl);
+            DataRow[] drs = dtAntiLink.Select("Domain='" + domain + "'");
+            if (drs.Length > 0)
+            {
+                foreach (DataRow dr in drs)
+                {
+                    switch (Convert.ToInt32(dr["Type"]))
+                    {
+                        case 1://置换
+                            sFormartted = sFormartted.Replace(dr["imgUrl"].ToString(), "http://stat.580k.com/t.asp?url=");
+                            break;
+                        default://附加
+                            sFormartted = sFormartted.Replace(dr["imgUrl"].ToString(), "http://stat.580k.com/t.asp?url=" + dr["imgUrl"].ToString());
+                            break;
+                    }
+                }
+            }
+
+            //A链接
+            sFormartted = _ReplaceUrl(@"<a[^>]+href\s*=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>", "href", sFormartted, sPageUrl);
+
+            //CSS
+            sFormartted = _ReplaceUrl(@"<link[^>]+href\s*=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>", "href", sFormartted, sPageUrl);
+
+            //BACKGROUND
+            sFormartted = _ReplaceUrl(@"background\s*=\s*(?:'(?<img>[^']+)'|""(?<img>[^""]+)""|(?<img>[^>\s]+))", "img", sFormartted, sPageUrl);
+            //style方式的背景:background-image:url(...)
+            sFormartted = _ReplaceUrl(@"background-image\s*:\s*url\s*\x28(?<img>[^\x29]+)\x29", "img", sFormartted, sPageUrl);
+
+            //FLASH
+            sFormartted = _ReplaceUrl(@"<param\s[^>]+""movie""[^>]+value\s*=\s*""(?<flash>[^"">]+\x2eswf)""[^>]*>", "flash", sFormartted, sPageUrl);
+
+            //XSL
+            if (IsXml(sFormartted))
+            {
+                sFormartted = _ReplaceUrl(@"<\x3fxml-stylesheet\s+[^\x3f>]+href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)"")\s*[^\x3f>]*\x3f>", "href", sFormartted, sPageUrl);
+            }
+
+            //script
+            //sFormartted = _ReplaceUrl(@"<script[^>]+src\s*=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>", "src", sFormartted,sPageUrl);
+
+            return sFormartted;
+        }
+
+        /// <summary>
+        /// 置换连接
+        /// </summary>
+        /// <param name="strRe"></param>
+        /// <param name="subMatch"></param>
+        /// <param name="sFormartted"></param>
+        /// <param name="sPageUrl"></param>
+        private static string _ReplaceUrl(string strRe, string subMatch, string sFormartted, string sPageUrl)
+        {
+            Regex re = new Regex(strRe, RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
+            MatchCollection mcs = re.Matches(sFormartted);
+            string sOriStr = "";
+            string sSubMatch = "";
+            string sReplaceStr = "";
+            foreach (Match mc in mcs)
+            {
+                sOriStr = mc.Value;
+                sSubMatch = mc.Groups[subMatch].Value;
+                sReplaceStr = sOriStr.Replace(sSubMatch, GetUrl(sPageUrl, sSubMatch));
+                sFormartted = sFormartted.Replace(sOriStr, sReplaceStr);
+            }
+
+            return sFormartted;
+        }
+
+        /// <summary>
+        /// 判断是否是xml格式
+        /// </summary>
+        /// <param name="sFormartted">输入内容</param>
+        /// <returns>是否是xml数据</returns>
+        public static bool IsXml(string sFormartted)
+        {
+            Regex re = new Regex(@"<\x3fxml\s+", RegexOptions.IgnoreCase);
+            MatchCollection mcs = re.Matches(sFormartted);
+            return mcs.Count > 0;
+        }
+
+        #endregion 根据表达式,获得文章内容
+
+        #region HTML相关操作
+        /// <summary>
+        /// 清除html标签
+        /// </summary>
+        /// <param name="sHtml">html代码</param>
+        /// <returns>清理后的内容</returns>
+        public static string ClearTag(string sHtml)
+        {
+            if (sHtml?.Length == 0)
+                return "";
+            string sTemp = sHtml;
+            Regex re = new Regex(@"(<[^>\s]*\b(\w)+\b[^>]*>)|(<>)|(&nbsp;)|(&gt;)|(&lt;)|(&amp;)|\r|\n|\t", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
+            return re.Replace(sHtml, "");
+        }
+        /// <summary>
+        /// 根据正则清除html标签
+        /// </summary>
+        /// <param name="sHtml">html代码</param>
+        /// <param name="sRegex">正则表达式</param>
+        /// <returns>清理后的内容</returns>
+        public static string ClearTag(string sHtml, string sRegex)
+        {
+            string sTemp = sHtml;
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
+            return re.Replace(sHtml, "");
+        }
+        /// <summary>
+        /// 将html转换成js代码
+        /// </summary>
+        /// <param name="sHtml">html代码</param>
+        /// <returns>js代码</returns>
+        public static string ConvertToJavascript(string sHtml)
+        {
+            StringBuilder sText = new StringBuilder();
+            var re = new Regex(@"\r\n", RegexOptions.IgnoreCase);
+            string[] strArray = re.Split(sHtml);
+            foreach (string strLine in strArray)
+            {
+                sText.Append("document.writeln(\"" + strLine.Replace("\"", "\\\"") + "\");\r\n");
+            }
+            return sText.ToString();
+        }
+
+        /// <summary>
+        /// 删除字符串中的特定标记 
+        /// </summary>
+        /// <param name="str">html代码</param>
+        /// <param name="tag">指定的标记</param>
+        /// <param name="isContent">是否清除内容 </param>
+        /// <returns>清理后的代码</returns>
+        public static string DelTag(string str, string tag, bool isContent)
+        {
+            if (tag == null || tag == " ")
+            {
+                return str;
+            }
+
+            if (isContent) //要求清除内容 
+            {
+                return Regex.Replace(str, string.Format("<({0})[^>]*>([\\s\\S]*?)<\\/\\1>", tag), "", RegexOptions.IgnoreCase);
+            }
+
+            return Regex.Replace(str, string.Format(@"(<{0}[^>]*(>)?)|(</{0}[^>] *>)|", tag), "", RegexOptions.IgnoreCase);
+        }
+
+        /// <summary>
+        /// 删除字符串中的一组标记 
+        /// </summary>
+        /// <param name="str">html代码</param>
+        /// <param name="tagA">标记</param>
+        /// <param name="isContent">是否清除内容 </param>
+        /// <returns>清理后的代码</returns>
+        public static string DelTagArray(string str, string tagA, bool isContent)
+        {
+            string[] tagAa = tagA.Split(',');
+            foreach (string sr1 in tagAa) //遍历所有标记,删除 
+            {
+                str = DelTag(str, sr1, isContent);
+            }
+            return str;
+        }
+
+        #endregion HTML相关操作
+
+        #region 根据内容获得链接
+        /// <summary>
+        /// 根据内容获得链接
+        /// </summary>
+        /// <param name="sContent">html代码</param>
+        /// <returns>链接</returns>
+        public static string GetLink(string sContent)
+        {
+            string strReturn = "";
+            Regex re = new Regex(@"<a\s+[^>]*href\s*=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
+            Regex js = new Regex(@"(href|onclick)=[^>]+javascript[^>]+(('(?<href>[\w\d/-]+\.[^']*)')|(&quot;(?<href>[\w\d/-]+\.[^;]*)&quot;))[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
+            Match mc = js.Match(sContent);//获取javascript中的链接,有待改进
+            if (mc.Success)
+            {
+                strReturn = mc.Groups["href"].Value;
+            }
+            else
+            {
+                Match me = re.Match(sContent);
+                if (me.Success)
+                {
+                    strReturn = System.Web.HttpUtility.HtmlDecode(me.Groups["href"].Value);
+                    //strReturn = RemoveByReg(strReturn, @";.*|javascript:.*");
+                    strReturn = RemoveByReg(strReturn, @";[^?&]*|javascript:.*");
+                }
+            }
+
+            return strReturn;
+        }
+        /// <summary>
+        /// 根据链接得到文本
+        /// </summary>
+        /// <param name="sContent">链接</param>
+        /// <returns>文本</returns>
+        public static string GetTextByLink(string sContent)
+        {
+            Regex re = new Regex(@"<a(?:\s+[^>]*)?>([\s\S]*)?</a>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Regex email = new Regex(@"(href|onclick)=[^>]+mailto[^>]+@[^>]+>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match me = email.Match(sContent);
+            if (me.Success)
+                return "";
+
+            Match mc = re.Match(sContent);
+            if (mc.Success)
+                return mc.Groups[1].Value;
+            else
+                return "";
+        }
+
+        private static void _GetLinks(string sContent, string sUrl, ref Dictionary<string, string> lisA)
+        {
+            const string sFilter =
+@"首页|下载|中文|English|反馈|讨论区|投诉|建议|联系|关于|about|诚邀|工作|简介|新闻|掠影|风采
+|登录|注销|注册|使用|体验|立即|收藏夹|收藏|添加|加入
+|更多|more|专题|精选|热卖|热销|推荐|精彩
+|加盟|联盟|友情|链接|相关
+|订阅|阅读器|RSS
+|免责|条款|声明|我的|我们|组织|概况|有限|免费|公司|法律|导航|广告|地图|隐私
+|〖|〗|【|】|(|)|[|]|『|』|\.";
+
+            Regex re = new Regex(@"<a\s+[^>]*href\s*=\s*[^>]+>[\s\S]*?</a>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Regex re2 = new Regex(@"""|'", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sContent);
+            //foreach (Match mc in mcs)
+            for (int i = mcs.Count - 1; i >= 0; i--)
+            {
+                Match mc = mcs[i];
+                string strHref = GetLink(mc.Value).Trim();
+
+                strHref = strHref.Replace("\\\"", "");//针对JS输出链接
+                strHref = strHref.Replace("\\\'", "");
+
+                string strTemp = RemoveByReg(strHref, @"^http.*/$");//屏蔽以“http”开头“/”结尾的链接地址
+                if (strTemp.Length < 2)
+                {
+                    continue;
+                }
+
+                //过滤广告或无意义的链接
+                string strText = ClearTag(GetTextByLink(mc.Value)).Trim();
+                strTemp = RemoveByReg(strText, sFilter);
+                if (Encoding.Default.GetBytes(strTemp).Length < 9)
+                {
+                    continue;
+                }
+                if (re2.IsMatch(strText))
+                {
+                    continue;
+                }
+
+                //换上绝对地址
+                strHref = GetUrlByRelative(sUrl, strHref);
+                if (strHref.Length <= 18)//例如,http://www.163.com = 18
+                {
+                    continue;
+                }
+
+                //计算#字符出现的位置,移除它后面的内容
+                //如果是域名地址,就跳过
+                int charIndex = strHref.IndexOf('#');
+                if (charIndex > -1)
+                {
+                    strHref = strHref.Substring(0, charIndex);
+                }
+                strHref = strHref.Trim(new char[] { '/', '\\' });
+                string tmpDomainURL = GetDomain(strHref);
+                if (strHref.Equals(tmpDomainURL, StringComparison.OrdinalIgnoreCase))
+                {
+                    continue;
+                }
+
+                if (!lisA.ContainsKey(strHref) && !lisA.ContainsValue(strText))
+                {
+                    lisA.Add(strHref, strText);
+                }
+            }
+        }
+
+        /// <summary>
+        /// 判断是否是js链接
+        /// </summary>
+        /// <param name="sHtml">html</param>
+        /// <returns></returns>
+        public static bool IsExistsScriptLink(string sHtml)
+        {
+            Regex re = new Regex(@"<script[^>]+src\s*=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
+            return re.IsMatch(sHtml);
+        }
+
+        /// <summary>
+        /// 从RSS FEED中读取
+        /// </summary>
+        /// <param name="sContent">RSS内容</param>
+        /// <param name="sUrl">URL</param>
+        /// <returns>读取到的内容</returns>
+        public static Dictionary<string, string> GetLinksFromRss(string sContent, string sUrl)
+        {
+            Dictionary<string, string> lisDes = new Dictionary<string, string>();
+            return GetLinksFromRss(sContent, sUrl, ref lisDes);
+        }
+
+        /// <summary>
+        /// 从RSS FEED中读取
+        /// </summary>
+        /// <param name="sContent">RSS内容</param>
+        /// <param name="sUrl">URL</param>
+        /// <param name="lisDes">过滤条件</param>
+        /// <returns>读取到的内容</returns>
+        public static Dictionary<string, string> GetLinksFromRss(string sContent, string sUrl, ref Dictionary<string, string> lisDes)
+        {
+            Dictionary<string, string> listResult = new Dictionary<string, string>();
+
+            XmlDocument xml = new XmlDocument();
+
+            //RSS2.0
+            try
+            {
+                xml.LoadXml(sContent.Trim());
+                XmlNodeList nodes = xml.SelectNodes("/rss/channel/item");
+                if (nodes.Count > 0)
+                {
+                    //for (int i = 0; i < nodes.Count; i++)
+                    for (int i = nodes.Count - 1; i >= 0; i--)
+                    {
+                        try
+                        {
+                            string sLink = GetUrlByRelative(sUrl, nodes[i].SelectSingleNode("link").InnerText);
+                            listResult.Add(sLink, nodes[i].SelectSingleNode("title").InnerText);
+                            lisDes.Add(sLink, nodes[i].SelectSingleNode("description").InnerText);
+                        }
+                        catch
+                        {
+                        }
+                    }
+                    return listResult;
+                }
+            }
+            catch
+            {
+            }
+
+            //RSS1.0(RDF)
+            try
+            {
+                XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable);
+                nsMgr.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
+                nsMgr.AddNamespace("rss", "http://purl.org/rss/1.0/");
+                XmlNodeList nodes = xml.SelectNodes("/rdf:RDF//rss:item", nsMgr);
+                if (nodes.Count > 0)
+                {
+                    for (int i = nodes.Count - 1; i >= 0; i--)
+                    {
+                        try
+                        {
+                            string sLink = GetUrlByRelative(sUrl, nodes[i].SelectSingleNode("rss:link", nsMgr).InnerText);
+                            listResult.Add(sLink, nodes[i].SelectSingleNode("rss:title", nsMgr).InnerText);
+                            lisDes.Add(sLink, nodes[i].SelectSingleNode("rss:description", nsMgr).InnerText);
+                        }
+                        catch
+                        {
+                        }
+                        //listResult.Add("<a href=\"" + nodes[i].SelectSingleNode("rss:link",nsMgr).InnerText + "\">" + nodes[i].SelectSingleNode("rss:title",nsMgr).InnerText + "</a>");
+                    }
+                    return listResult;
+                }
+            }
+            catch
+            {
+            }
+
+            //RSS ATOM
+            try
+            {
+                XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable);
+                nsMgr.AddNamespace("atom", "http://purl.org/atom/ns#");
+                XmlNodeList nodes = xml.SelectNodes("/atom:feed/atom:entry", nsMgr);
+                if (nodes.Count > 0)
+                {
+                    for (int i = nodes.Count - 1; i >= 0; i--)
+                    {
+                        try
+                        {
+                            string sLink = GetUrlByRelative(sUrl, nodes[i].SelectSingleNode("atom:link", nsMgr).Attributes["href"].InnerText);
+                            listResult.Add(sLink, nodes[i].SelectSingleNode("atom:title", nsMgr).InnerText);
+                            lisDes.Add(sLink, nodes[i].SelectSingleNode("atom:content", nsMgr).InnerText);
+                        }
+                        catch
+                        {
+                        }
+                        //listResult.Add("<a href=\"" + nodes[i].SelectSingleNode("atom:link",nsMgr).Attributes["href"].InnerText + "\">" + nodes[i].SelectSingleNode("atom:title",nsMgr).InnerText + "</a>");
+                    }
+                    return listResult;
+                }
+            }
+            catch
+            {
+            }
+
+            return listResult;
+        }
+        /// <summary>
+        ///  从RSS FEED中读取标题
+        /// </summary>
+        /// <param name="sContent">RSS</param>
+        /// <returns>标题</returns>
+        public static string GetTitleFromRss(string sContent)
+        {
+            string title = "";
+            XmlDocument xml = new XmlDocument();
+
+            //RSS2.0
+            try
+            {
+                xml.LoadXml(sContent.Trim());
+                title = xml.SelectSingleNode("/rss/channel/title").InnerText;
+            }
+            catch
+            {
+            }
+
+            return title;
+        }
+
+        /// <summary>
+        /// 根据标签进行移除
+        /// </summary>
+        /// <param name="sContent">html</param>
+        /// <param name="sRegex">正则表达式</param>
+        /// <returns>清理后的代码</returns>
+        public static string RemoveByReg(string sContent, string sRegex)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sContent);
+            foreach (Match mc in mcs)
+            {
+                sContent = sContent.Replace(mc.Value, "");
+            }
+            return sContent;
+        }
+
+        /// <summary>
+        /// 根据正则表达式替换内容
+        /// </summary>
+        /// <param name="sContent">html</param>
+        /// <param name="sReplace">需要替换的内容</param>
+        /// <param name="sRegex">符合正则的内容</param>
+        /// <returns>替换后内容</returns>
+        public static string ReplaceByReg(string sContent, string sReplace, string sRegex)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            sContent = re.Replace(sContent, sReplace);
+            return sContent;
+        }
+
+        /// <summary>
+        ///  网页Body内容
+        /// </summary>
+        /// <param name="sContent"></param>
+        /// <returns></returns>
+        public static string GetBody(string sContent)
+        {
+            Regex re = new Regex(@"[\s\S]*?<\bbody\b[^>]*>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
+            sContent = re.Replace(sContent, "");
+
+            re = new Regex(@"</\bbody\b[^>]*>\s*</html>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.RightToLeft);
+            sContent = re.Replace(sContent, "");
+            return sContent;
+        }
+        #endregion 根据超链接地址获取页面内容
+
+        #region 根据内容作字符串分析
+        /// <summary>
+        /// 根据标签获取文本
+        /// </summary>
+        /// <param name="sContent">html</param>
+        /// <param name="sRegex">正则表达式</param>
+        /// <returns>文本</returns>
+        public static string GetTextByReg(string sContent, string sRegex)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match mc = re.Match(sContent);
+            string str = "";
+            if (mc.Success)
+                str = mc.Groups[0].Value;
+            while (str.EndsWith("_"))
+            {
+                str = RemoveEndWith(str, "_");
+            }
+            return str;
+        }
+
+        // charset=[\s]*(?<Coding>[^'"]+)[\s]*['"]?[\s]*[/]?>
+        /// <summary>
+        /// 根据标签获取文本
+        /// </summary>
+        /// <param name="sContent">html</param>
+        /// <param name="sRegex">正则表达式</param>
+        /// <param name="sGroupName">分组名</param>
+        /// <returns>文本</returns>
+        public static string GetTextByReg(string sContent, string sRegex, string sGroupName)
+        {
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            Match mc = re.Match(sContent);
+            string str = "";
+            if (mc.Success)
+                str = mc.Groups[sGroupName].Value;
+            return str;
+        }
+
+        /// <summary>
+        /// 获得链接的绝对路径
+        /// </summary>
+        /// <param name="sUrl"></param>
+        /// <param name="sRUrl"></param>
+        /// <returns></returns>
+        public static string GetUrlByRelative(string sUrl, string sRUrl)
+        {
+            try
+            {
+                //http://q.yesky.com/grp/dsc/view.do;jsessionid=A6324FD46B4893303124F70C0B2AAC1E?grpId=201595&rvId=8215876
+                Uri baseUri = new Uri(sUrl);
+                if (!sUrl.EndsWith("/"))
+                {
+                    int i = baseUri.Segments.Length - 1;
+                    if (i > 0)
+                    {
+                        string file = baseUri.Segments[i];
+                        if (file.IndexOf('.') < 1)
+                        {
+                            baseUri = new Uri(sUrl + "/");
+                        }
+                    }
+                }
+                Uri myUri = new Uri(baseUri, sRUrl);
+                return myUri.AbsoluteUri;
+            }
+            catch
+            {
+                return sUrl;
+            }
+        }
+
+        /// <summary>
+        /// 根据标签获取数据集合
+        /// </summary>
+        /// <param name="sContent">html</param>
+        /// <param name="sRegex">正则表达式</param>
+        /// <returns>数据集合</returns>
+        public static List<string> GetListByReg(string sContent, string sRegex)
+        {
+            List<string> list = new List<string>();
+            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
+            MatchCollection mcs = re.Matches(sContent);
+            foreach (Match mc in mcs)
+            {
+                list.Add(mc.Groups["href"].Value);
+            }
+            return list;
+        }
+
+        /// <summary>
+        /// 获得主域
+        /// </summary>
+        /// <param name="sUrl">URL</param>
+        /// <returns>域名</returns>
+        public static string GetDomainUrl(string sUrl)
+        {
+            try
+            {
+                Uri baseUri = new Uri(sUrl);
+
+                return baseUri.Scheme + "://" + baseUri.Authority;
+            }
+            catch
+            {
+                return sUrl;
+            }
+        }
+
+        #endregion
+
+        #region 杂项
+
+        /// <summary>
+        /// 从html中过滤出文本
+        /// </summary>
+        /// <param name="sHtml">html</param>
+        /// <returns>纯文本</returns>
+        public static string GetTxtFromHtml(string sHtml)
+        {
+            string del = @"<head[^>]*>[\s\S]*?</head>";
+            string content = RemoveByReg(sHtml, del);
+
+            del = @"(<script[^>]*>[\s\S]*?</script>)|(<IFRAME[^>]*>[\s\S]*?</IFRAME>)|(<style[^>]*>[\s\S]*?</style>|<title[^>]*>[\s\S]*?</title>|<meta[^>]*>|<option[^>]*>[\s\S]*?</option>)";
+            content = RemoveByReg(content, del);
+
+            del = @"(&nbsp;)|([\n\t]+)";
+            content = RemoveByReg(content, del);
+
+            string re = @"(<table(\s+[^>]*)*>)|(<td(\s+[^>]*)*>)|(<tr(\s+[^>]*)*>)|(<p(\s+[^>]*)*>)|(<div(\s+[^>]*)*>)|(<ul(\s+[^>]*)*>)|(<li(\s+[^>]*)*>)|</table>|</td>|</tr>|</p>|<br>|</div>|</li>|</ul>|<p />|<br />";
+            content = ReplaceByReg(content, "", re);
+            content = ReplaceByReg(content, "", @"[\f\n\r\v]+");
+
+            content = RemoveByReg(content, @"<a(\s+[^>]*)*>[\s\S]*?</a>");
+            content = RemoveByReg(content, "<[^>]+>");//去除各种HTML标记,获得纯内容
+
+            content = content.Replace("\n", "");
+            content = content.Replace("\r", "");
+            content = content.Trim();
+            return content;
+        }
+
+        /// <summary>
+        /// 和GetTxtFromHtml功能一样,不过保留换行符号
+        /// </summary>
+        /// <param name="sHtml"></param>
+        /// <returns></returns>
+        public static string GetTxtFromHtml2(string sHtml)
+        {
+            string del = @"<head[^>]*>[\s\S]*?</head>";
+            string content = RemoveByReg(sHtml, del);
+
+            del = @"(<script[^>]*>[\s\S]*?</script>)|(<IFRAME[^>]*>[\s\S]*?</IFRAME>)|(<style[^>]*>[\s\S]*?</style>|<title[^>]*>[\s\S]*?</title>|<meta[^>]*>|<option[^>]*>[\s\S]*?</option>)";
+            content = RemoveByReg(content, del);
+
+            del = @"(&nbsp;)|([\t]+)";//del = @"(&nbsp;)|([\n\t]+)";
+            content = RemoveByReg(content, del);
+
+            string re = @"(<table(\s+[^>]*)*>)|(<td(\s+[^>]*)*>)|(<tr(\s+[^>]*)*>)|(<p(\s+[^>]*)*>)|(<div(\s+[^>]*)*>)|(<ul(\s+[^>]*)*>)|(<li(\s+[^>]*)*>)|</table>|</td>|</tr>|</p>|<br>|</div>|</li>|</ul>|<p />|<br />";
+            content = ReplaceByReg(content, "", re);
+            //content = CText.ReplaceByReg(content, "", @"[\f\n\r\v]+");
+
+            content = RemoveByReg(content, @"<a(\s+[^>]*)*>[\s\S]*?</a>");
+            content = RemoveByReg(content, "<[^>]+>");//去除各种HTML标记,获得纯内容
+            content = content.Trim();
+
+            return content;
+        }
+        #endregion
+
+        /// <summary>
+        /// 按结尾移除内容
+        /// </summary>
+        /// <param name="sOrg">原始数据</param>
+        /// <param name="sEnd">结束的字符串</param>
+        /// <returns>清理后的内容</returns>
+        public static string RemoveEndWith(string sOrg, string sEnd)
+        {
+            if (sOrg.EndsWith(sEnd))
+                sOrg = sOrg.Remove(sOrg.IndexOf(sEnd), sEnd.Length);
+            return sOrg;
+        }
+
+        #region 根据超链接地址获取页面内容
+        /// <summary>
+        /// 根据超链接地址获取页面内容
+        /// </summary>
+        /// <param name="sUrl">URL</param>
+        /// <returns>页面内容</returns>
+        public static string GetHtmlByUrl(string sUrl)
+        {
+            return GetHtmlByUrl(sUrl, "auto");
+        }
+
+        /// <summary>
+        /// 根据超链接地址获取页面内容
+        /// </summary>
+        /// <param name="sUrl">URL</param>
+        /// <param name="sCoding">文件编码</param>
+        /// <returns>页面内容</returns>
+        public static string GetHtmlByUrl(string sUrl, string sCoding)
+        {
+            return GetHtmlByUrl(ref sUrl, sCoding);
+        }
+
+        /// <summary>
+        /// 根据超链接地址获取页面内容,并将url作为引用类型
+        /// </summary>
+        /// <param name="sUrl">URL</param>
+        /// <param name="sCoding">文件编码</param>
+        /// <returns>页面内容</returns>
+        public static string GetHtmlByUrl(ref string sUrl, string sCoding)
+        {
+            string content = "";
+
+            try
+            {
+                HttpWebResponse response = _MyGetResponse(sUrl);
+                if (response == null)
+                {
+                    return content;
+                }
+
+                sUrl = response.ResponseUri.AbsoluteUri;
+
+                Stream stream = response.GetResponseStream();
+                byte[] buffer = GetContent(stream);
+                stream.Close();
+                stream.Dispose();
+
+                string charset = "";
+                if (string.IsNullOrEmpty(sCoding) || string.Equals(sCoding, "auto", StringComparison.CurrentCultureIgnoreCase))
+                {//如果不指定编码,那么系统代为指定
+                    //首先,从返回头信息中寻找
+                    string ht = response.GetResponseHeader("Content-Type");
+                    response.Close();
+                    string regCharSet = "[\\s\\S]*charset=(?<charset>[\\S]*)";
+                    Regex r = new Regex(regCharSet, RegexOptions.IgnoreCase);
+                    Match m = r.Match(ht);
+                    charset = (m.Captures.Count != 0) ? m.Result("${charset}") : "";
+                    if (charset == "-8") charset = "utf-8";
+                    if (charset?.Length == 0)
+                    {//找不到,则在文件信息本身中查找
+                        //先按gb2312来获取文件信息
+                        content = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
+
+                        regCharSet = "(<meta[^>]*charset=(?<charset>[^>'\"]*)[\\s\\S]*?>)|(xml[^>]+encoding=(\"|')*(?<charset>[^>'\"]*)[\\s\\S]*?>)";
+                        r = new Regex(regCharSet, RegexOptions.IgnoreCase);
+                        m = r.Match(content);
+                        if (m.Captures.Count == 0)
+                        {//没办法,都找不到编码,只能返回按"gb2312"获取的信息
+                            //content = CText.RemoveByReg(content, @"<!--[\s\S]*?-->");
+                            return content;
+                        }
+                        charset = m.Result("${charset}");
+                    }
+                }
+                else
+                {
+                    response.Close();
+                    charset = sCoding.ToLower();
+                }
+
+                try
+                {
+                    content = System.Text.Encoding.GetEncoding(charset).GetString(buffer);
+                }
+                catch (ArgumentException)
+                {//指定的编码不可识别
+                    content = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
+                }
+
+                //content = CText.RemoveByReg(content, @"<!--[\s\S]*?-->");
+            }
+            catch
+            {
+                content = "";
+            }
+
+            return content;
+        }
+
+        private static HttpWebResponse _MyGetResponse(string sUrl)
+        {
+            int iTimeOut = 10000;
+            //try
+            //{
+            //    //iTimeOut = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SocketTimeOut"]);
+            //}
+            //catch { iTimeOut = 10000; }
+
+            bool bCookie = false;
+            bool bRepeat = false;
+            Uri target = new Uri(sUrl);
+
+ReCatch:
+            try
+            {
+                HttpWebRequest resquest = (HttpWebRequest)WebRequest.Create(target);
+                resquest.MaximumResponseHeadersLength = -1;
+                resquest.ReadWriteTimeout = 120000;//120秒就超时
+                resquest.Timeout = iTimeOut;
+                resquest.MaximumAutomaticRedirections = 50;
+                resquest.MaximumResponseHeadersLength = 5;
+                resquest.AllowAutoRedirect = true;
+                if (bCookie)
+                {
+                    resquest.CookieContainer = new CookieContainer();
+                }
+                resquest.UserAgent = "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1)";
+                //resquest.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1) Web-Sniffer/1.0.24";
+                //resquest.KeepAlive = true;
+                return (HttpWebResponse)resquest.GetResponse();
+            }
+            catch (WebException)
+            {
+                if (!bRepeat)
+                {
+                    bRepeat = true;
+                    bCookie = true;
+                    goto ReCatch;
+                }
+                return null;
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        private static byte[] GetContent(Stream stream)
+        {
+            ArrayList arBuffer = new ArrayList();
+            const int BUFFSIZE = 4096;
+
+            try
+            {
+                byte[] buffer = new byte[BUFFSIZE];
+                int count = stream.Read(buffer, 0, BUFFSIZE);
+                while (count > 0)
+                {
+                    for (int i = 0; i < count; i++)
+                    {
+                        arBuffer.Add(buffer[i]);
+                    }
+                    count = stream.Read(buffer, 0, BUFFSIZE);
+                }
+            }
+            catch
+            {
+            }
+
+            return (byte[])arBuffer.ToArray(System.Type.GetType("System.Byte"));
+        }
+
+        /// <summary>
+        /// 获取http报文头
+        /// </summary>
+        /// <param name="sUrl">URL</param>
+        /// <returns>报文信息</returns>
+        public static string GetHttpHead(string sUrl)
+        {
+            string sHead = "";
+            Uri uri = new Uri(sUrl);
+            try
+            {
+                WebRequest req = WebRequest.Create(uri);
+                WebResponse resp = req.GetResponse();
+                WebHeaderCollection headers = resp.Headers;
+                string[] sKeys = headers.AllKeys;
+                foreach (string sKey in sKeys)
+                {
+                    sHead += sKey + ":" + headers[sKey] + "\r\n";
+                }
+            }
+            catch
+            {
+            }
+            return sHead;
+        }
+
+        /// <summary>
+        /// 处理框架页面问题。如果该页面是框架结构的话,返回该框架
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <param name="content">内容</param>
+        /// <returns>框架结构</returns>
+        public static string[] DealWithFrame(string url, string content)
+        {
+            string regFrame = @"<frame\s+[^>]*src\s*=\s*(?:""(?<src>[^""]+)""|'(?<src>[^']+)'|(?<src>[^\s>""']+))[^>]*>";
+            return DealWithFrame(regFrame, url, content);
+        }
+
+        /// <summary>
+        /// 处理浮动桢问题。如果该页面存在浮动桢,返回浮动桢
+        /// </summary>
+        /// <param name="url">URL</param>
+        /// <param name="content">内容</param>
+        /// <returns>浮动桢</returns>
+        public static string[] DealWithIFrame(string url, string content)
+        {
+            string regiFrame = @"<iframe\s+[^>]*src\s*=\s*(?:""(?<src>[^""]+)""|'(?<src>[^']+)'|(?<src>[^\s>""']+))[^>]*>";
+            return DealWithFrame(regiFrame, url, content);
+        }
+
+        private static string[] DealWithFrame(string strReg, string url, string content)
+        {
+            ArrayList alFrame = new ArrayList();
+            Regex r = new Regex(strReg, RegexOptions.IgnoreCase);
+            Match m = r.Match(content);
+            while (m.Success)
+            {
+                alFrame.Add(GetUrl(url, m.Groups["src"].Value));
+                m = m.NextMatch();
+            }
+
+            return (string[])alFrame.ToArray(System.Type.GetType("System.String"));
+        }
+
+        #endregion 根据超链接地址获取页面内容
+
+        #region 获得多个页面
+        /// <summary>
+        /// 获得多个页面
+        /// </summary>
+        /// <param name="listUrl">URL集合</param>
+        /// <param name="sCoding">文件编码</param>
+        /// <returns>页面集合</returns>
+        /// <exception cref="Exception"></exception>
+        public static List<KeyValuePair<int, string>> GetHtmlByUrlList(List<KeyValuePair<int, string>> listUrl, string sCoding)
+        {
+            int iTimeOut = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SocketTimeOut"]);
+            StringBuilder sbHtml = new StringBuilder();
+            List<KeyValuePair<int, string>> listResult = new List<KeyValuePair<int, string>>();
+            int nBytes = 0;
+            Socket sock = null;
+            IPHostEntry ipHostInfo = null;
+            try
+            {
+                // 初始化				
+                Uri site = new Uri(listUrl[0].Value);
+                ipHostInfo = System.Net.Dns.GetHostEntry(site.Host);
+                IPAddress ipAddress = ipHostInfo.AddressList[0];
+                IPEndPoint remoteEP = new IPEndPoint(ipAddress, site.Port);
+                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                sock.SendTimeout = iTimeOut;
+                sock.ReceiveTimeout = iTimeOut;
+                sock.Connect(remoteEP);
+                foreach (KeyValuePair<int, string> kvUrl in listUrl)
+                {
+                    site = new Uri(kvUrl.Value);
+                    string sendMsg = "GET " + HttpUtility.UrlDecode(site.PathAndQuery) + " HTTP/1.1\r\n" +
+                        "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */*\r\n" +
+                        "Accept-Language:en-us\r\n" +
+                        "Accept-Encoding:gb2312, deflate\r\n" +
+                        "User-Agent: Mozilla/4.0\r\n" +
+                        "Host: " + site.Host + "\r\n\r\n" + '\0';
+                    // 发送
+                    byte[] msg = Encoding.GetEncoding(sCoding).GetBytes(sendMsg);
+                    if ((nBytes = sock.Send(msg)) == 0)
+                    {
+                        sock.Shutdown(SocketShutdown.Both);
+                        sock.Close();
+                        return listResult;
+                    }
+                    // 接受
+                    byte[] bytes = new byte[2048];
+                    byte bt = Convert.ToByte('\x7f');
+                    do
+                    {
+                        int count = 0;
+                        try
+                        {
+                            nBytes = sock.Receive(bytes, bytes.Length - 1, 0);
+                        }
+                        catch (Exception Ex)
+                        {
+                            string str = Ex.Message;
+                            nBytes = -1;
+                        }
+                        if (nBytes <= 0) break;
+                        if (bytes[nBytes - 1] > bt)
+                        {
+                            for (int i = nBytes - 1; i >= 0; i--)
+                            {
+                                if (bytes[i] > bt)
+                                    count++;
+                                else
+                                    break;
+                            }
+                            if (count % 2 == 1)
+                            {
+                                count = sock.Receive(bytes, nBytes, 1, 0);
+                                if (count < 0)
+                                    break;
+                                nBytes += count;
+                            }
+                        }
+                        else
+                        {
+                            bytes[nBytes] = (byte)'\0';
+                        }
+
+                        string s = Encoding.GetEncoding(sCoding).GetString(bytes, 0, nBytes);
+                        sbHtml.Append(s);
+                    } while (nBytes > 0);
+
+                    listResult.Add(new KeyValuePair<int, string>(kvUrl.Key, sbHtml.ToString()));
+                    sbHtml = null;
+                    sbHtml = new StringBuilder();
+                }
+            }
+            catch (Exception Ex)
+            {
+                string s = Ex.Message;
+                try
+                {
+                    sock.Shutdown(SocketShutdown.Both);
+                    sock.Close();
+                }
+                catch
+                {
+                }
+            }
+            finally
+            {
+                try
+                {
+                    sock.Shutdown(SocketShutdown.Both);
+                    sock.Close();
+                }
+                catch
+                {
+                }
+            }
+            return listResult;
+        }
+        #endregion 根据超链接地址获取页面内容
+
+        /// <summary>
+        /// 页面类型枚举
+        /// </summary>
+        public enum PageType : int
+        {
+            /// <summary>
+            /// HTML格式
+            /// </summary>
+            HTML = 0,
+            /// <summary>
+            /// RSS格式
+            /// </summary>
+            RSS = 1
+        }
+        /// <summary>
+        /// 获取页面类型
+        /// </summary>
+        /// <param name="sUrl">URL</param>
+        /// <param name="sHtml">内容</param>
+        /// <returns>页面类型枚举</returns>
+        public static PageType GetPageType(string sUrl, ref string sHtml)
+        {
+            PageType pt = PageType.HTML;
+
+            //看有没有RSS FEED
+            string regRss = @"<link\s+[^>]*((type=""application/rss\+xml"")|(type=application/rss\+xml))[^>]*>";
+            Regex r = new Regex(regRss, RegexOptions.IgnoreCase);
+            Match m = r.Match(sHtml);
+            if (m.Captures.Count != 0)
+            {//有,则转向从RSS FEED中抓取
+                string regHref = @"href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))";
+                r = new Regex(regHref, RegexOptions.IgnoreCase);
+                m = r.Match(m.Captures[0].Value);
+                if (m.Captures.Count > 0)
+                {
+                    //有可能是相对路径,加上绝对路径
+                    string rssFile = GetUrl(sUrl, m.Groups["href"].Value);
+                    sHtml = GetHtmlByUrl(rssFile);
+                    pt = PageType.RSS;
+                }
+            }
+            else
+            {//看这个地址本身是不是一个Rss feed
+                r = new Regex(@"<rss\s+[^>]*>", RegexOptions.IgnoreCase);
+                m = r.Match(sHtml);
+                if (m.Captures.Count > 0)
+                {
+                    pt = PageType.RSS;
+                }
+            }
+
+            return pt;
+        }
+    }
+}

+ 235 - 0
Masuit.Tools/Html/ListBuilder.cs

@@ -0,0 +1,235 @@
+using System.Data;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Masuit.Tools.Html
+{
+    /*  使用方式         
+    ListBuilder lb1=new ListBuilder("ul");
+    lb1.SetTemplate("<a href=\"{#url}\" target=\"_blank\"><strong>{#sortName}</strong></a>\r\n{#lb2}");
+
+    ListBuilder lb2=new ListBuilder("ul");
+    lb2.SetTemplate("<a href=\""+url+"?tid={#id}"+"\" target=\"_blank\">{#title}</a> <span class='date'>[{#date}]</span>");
+    lb2.BindData(dt2);
+    或者
+    lb1.AddTemplateData("sortName",dr["sortName"].ToString());
+    lb1.AddTemplateData("url",url+"#sid."+dr["id"].ToString()+"/page.1/");
+    lb1.AddTemplateData("lb2",lb2.ToString());
+    lb1.EndTemplateData();
+    lSitemap.Text=lb1.ToString();
+ */
+    /// <summary>
+    /// 无序列表生成器
+    /// </summary>
+    public class ListBuilder
+    {
+        private string type = "dl";
+        private StringBuilder sb = new StringBuilder();
+        private string template = string.Empty;
+        private System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
+
+        /// <summary>
+        /// 构造函数
+        /// </summary>
+        /// <param name="_type">列表类型,可选"ul","dl",默认"ul"</param>
+        /// <param name="className"></param>
+        public ListBuilder(string _type, string className)
+        {
+            if (_type != string.Empty) type = _type;
+            if (className != string.Empty) className = " class='" + className + "'";
+            sb.Append("<" + type + className + ">");
+        }
+        /// <summary>
+        /// 以ul构造列表
+        /// </summary>
+        public ListBuilder()
+        {
+            sb.Append("<dl>");
+        }
+        /// <summary>
+        /// 构造函数
+        /// </summary>
+        /// <param name="_type">列表类型,可选"ul","dl",默认"ul"</param>
+        public ListBuilder(string _type)
+        {
+            type = _type;
+            sb.Append("<" + type + ">");
+        }
+
+        /// <summary>
+        /// 设置模版
+        /// </summary>
+        /// <param name="_template">模版,以{#name}作为参数,name来自数据源datatable或者执行设置</param>
+        public void SetTemplate(string _template)
+        {
+            template = _template;
+        }
+
+        /// <summary>
+        /// 添加模版数据
+        /// </summary>
+        /// <param name="name">名称</param>
+        /// <param name="value">值</param>
+        public void AddTemplateData(string name, string value)
+        {
+            nvc.Add(name, value);
+        }
+
+        /// <summary>
+        /// 模版数据添加完成后需调用此方法
+        /// </summary>
+        /// <param name="className">列表项(li或者dd)的css类名</param>
+        public void EndTemplateData(string className)
+        {
+            string itemName = "dd";
+            if (type != "dl")
+            {
+                itemName = "li";
+            }
+            if (className != string.Empty) className = " class='" + className + "'";
+            sb.Append("<" + itemName + className + ">");
+            sb.Append(GenerateString());
+            sb.Append("</" + itemName + ">");
+            nvc.Clear();
+        }
+
+        /// <summary>
+        /// 模版数据添加完成后需调用此方法
+        /// </summary>
+        public void EndTemplateData()
+        {
+            EndTemplateData("");
+        }
+
+        /// <summary>
+        /// 生成字符串返回
+        /// </summary>
+        /// <returns>生成后的内容</returns>
+        protected string GenerateString()
+        {
+            Regex regex = new Regex(@"{#(\w+)}", RegexOptions.IgnoreCase);
+            return regex.Replace(template, new MatchEvaluator(this.MatchEvaluator));
+        }
+
+        /// <summary>
+        /// 正则匹配中的委托定义
+        /// </summary>
+        /// <param name="m"></param>
+        /// <returns></returns>
+        protected string MatchEvaluator(Match m)
+        {
+            string name = m.Groups[1].Captures[0].Value;
+            return nvc[name];
+        }
+
+        /// <summary>
+        /// 设置标题
+        /// </summary>
+        /// <param name="text">文本</param>
+        /// <param name="url">链接</param>
+        /// <param name="target">目标窗口,可选"_blank","_self"等,默认"_self"</param>
+        public void SetTitle(string text, string url, string target)
+        {
+            this.SetTitle(text, url, target, "");
+        }
+        /// <summary>
+        /// 设置标题
+        /// </summary>
+        /// <param name="text">文本</param>
+        /// <param name="url">链接</param>
+        public void SetTitle(string text, string url)
+        {
+            this.SetTitle(text, url, "", "");
+        }
+        /// <summary>
+        /// 设置纯文本标题
+        /// </summary>
+        /// <param name="text">文本</param>
+        public void SetTitle(string text)
+        {
+            this.SetTitle(text, "", "", "");
+        }
+        /// <summary>
+        /// 设置标题
+        /// </summary>
+        /// <param name="text">文本</param>
+        /// <param name="url">链接</param>
+        /// <param name="target">目标窗口,可选"_blank","_self"等,默认"_self"</param>
+        /// <param name="className">CSS类名</param>
+        public void SetTitle(string text, string url, string target, string className)
+        {
+            string itemName = "dt";
+            if (type != "dl")
+            {
+                itemName = "li";
+                className += " title ";
+            }
+            if (className != string.Empty) className = " class='" + className + "'";
+            sb.Append("<" + itemName + className + ">");
+            if (url?.Length == 0)
+            {
+                sb.Append(text);
+            }
+            else
+            {
+                if (target != string.Empty) target = " target='" + target + "'";
+                sb.Append("<a href='" + url + "'" + target + ">");
+                sb.Append(text);
+                sb.Append("</a>");
+            }
+            sb.Append("</" + itemName + ">");
+        }
+        /// <summary>
+        /// 添加一项
+        /// </summary>
+        /// <param name="text">文本</param>
+        /// <param name="url">链接</param>
+        /// <param name="target">目标窗口,可选"_blank","_self"等,默认"_self"</param>
+        /// <param name="className">CSS类名</param>
+        public void AddItem(string text, string url, string target, string className)
+        {
+            string itemName = "dd";
+            if (type != "dl") itemName = "li";
+            if (className != string.Empty) className = " class='" + className + "'";
+            sb.Append("<" + itemName + className + ">");
+            if (url?.Length == 0)
+            {
+                sb.Append(text);
+            }
+            else
+            {
+                if (target != string.Empty) target = " target='" + target + "'";
+                sb.Append("<a href='" + url + "'" + target + ">");
+                sb.Append(text);
+                sb.Append("</a>");
+            }
+            sb.Append("</" + itemName + ">");
+        }
+
+        /// <summary>
+        /// 返回列表的HTML
+        /// </summary>
+        /// <returns>列表的HTML</returns>
+        public override string ToString()
+        {
+            sb.Append("</" + type + ">");
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 根据模板绑定一个dataTable,使用datatable中的值来填充模板
+        /// </summary>
+        /// <param name="dataTable"></param>
+        public void BindData(System.Data.DataTable dataTable)
+        {
+            foreach (System.Data.DataRow dr in dataTable.Rows)
+            {
+                foreach (DataColumn column in dataTable.Columns)
+                {
+                    AddTemplateData(column.ColumnName, dr[column.ColumnName].ToString());
+                }
+                EndTemplateData();
+            }
+        }
+    }
+}

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

@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{275D5A0D-C49C-497E-A4B5-F40285C2495F}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Masuit.Tools</RootNamespace>
+    <AssemblyName>Masuit.Tools</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <NuGetPackageImportStamp>
+    </NuGetPackageImportStamp>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <DocumentationFile>bin\Debug\Masuit.Tools.XML</DocumentationFile>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <DocumentationFile>bin\Release\Masuit.Tools.XML</DocumentationFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Aspose.Words, Version=17.2.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56, processorArchitecture=MSIL">
+      <HintPath>..\packages\Aspose.Words.17.2.0\lib\net40\Aspose.Words.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="ConDep.Dsl, Version=4.0.7.0, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\packages\ConDep.Dsl.4.0.7\lib\net40\ConDep.Dsl.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="ICSharpCode.SharpZipLib, Version=0.86.0.518, Culture=neutral, PublicKeyToken=1b03e6acf1164f73, processorArchitecture=MSIL">
+      <HintPath>..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
+      <HintPath>..\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+      <HintPath>..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="SlowCheetah.Tasks, Version=1.0.10727.0, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\packages\SlowCheetah.Tasks.Unofficial.1.0.0\lib\SlowCheetah.Tasks.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="StackExchange.Redis, Version=1.2.0.0, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\packages\StackExchange.Redis.1.2.0\lib\net45\StackExchange.Redis.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Configuration" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.IO.Compression" />
+    <Reference Include="System.Management" />
+    <Reference Include="System.Net" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Net.Http.Extensions, Version=2.2.29.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Extensions.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.AspNet.WebApi.Client.4.0.30506.0\lib\net40\System.Net.Http.Formatting.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System.Net.Http.Primitives, Version=4.2.29.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Primitives.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System.Web" />
+    <Reference Include="System.Web.Extensions" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <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\TimeHelper.cs" />
+    <Compile Include="Files\Compress.cs" />
+    <Compile Include="Files\DocumentConvert.cs" />
+    <Compile Include="Files\ExtensionAttach.cs" />
+    <Compile Include="Files\FileTree.cs" />
+    <Compile Include="Files\INIFile.cs" />
+    <Compile Include="Html\HtmlHelper.cs" />
+    <Compile Include="Html\HtmlPager.cs" />
+    <Compile Include="Html\HtmlTools.cs" />
+    <Compile Include="Html\HtmlUtils.cs" />
+    <Compile Include="Html\ListBuilder.cs" />
+    <Compile Include="Net\CacheHelper.cs" />
+    <Compile Include="Net\CookieHelper.cs" />
+    <Compile Include="Net\SocketClient.cs" />
+    <Compile Include="Reflection\ReflectHelper.cs" />
+    <Compile Include="Reflection\ReflectionUtil.cs" />
+    <Compile Include="Security\AESEncode.cs" />
+    <Compile Include="Security\Encrypt.cs" />
+    <Compile Include="Files\FileExt.cs" />
+    <Compile Include="Hardware\SystemInfo.cs" />
+    <Compile Include="Media\ImageUtilities.cs" />
+    <Compile Include="Models\AsposeLicense.cs" />
+    <Compile Include="Models\Email.cs" />
+    <Compile Include="Models\INetAddress.cs" />
+    <Compile Include="Models\IPData.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Net\RedisHelper.cs" />
+    <Compile Include="Security\HashEncode.cs" />
+    <Compile Include="Security\RSACryption.cs" />
+    <Compile Include="Strings\ConvertJson.cs" />
+    <Compile Include="Strings\JsonHelper.cs" />
+    <Compile Include="Strings\StringExt.cs" />
+    <Compile Include="Strings\ValidateCode.cs" />
+    <Compile Include="Net\WebExtension.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="app.config" />
+    <None Include="packages.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="DateTimeExt\CCalendarData.xml" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <Import Project="..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
+  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
+    <PropertyGroup>
+      <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
+    </PropertyGroup>
+    <Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets'))" />
+  </Target>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>

+ 1251 - 0
Masuit.Tools/Media/ImageUtilities.cs

@@ -0,0 +1,1251 @@
+using System;
+using System.Collections;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Threading.Tasks;
+
+namespace Masuit.Tools.Media
+{
+    /// <summary>
+    /// 图片处理
+    /// </summary>
+    public static class ImageUtilities
+    {
+        #region 正方型裁剪并缩放
+
+        /// <summary>
+        /// 正方型裁剪
+        /// 以图片中心为轴心,截取正方型,然后等比缩放
+        /// 用于头像处理
+        /// </summary>
+        /// <param name="fromFile">原图Stream对象</param>
+        /// <param name="fileSaveUrl">缩略图存放地址</param>
+        /// <param name="side">指定的边长(正方型)</param>
+        /// <param name="quality">质量(范围0-100)</param>
+        public static void CutForSquare(Stream fromFile, string fileSaveUrl, int side, int quality)
+        {
+            //创建目录
+            string dir = Path.GetDirectoryName(fileSaveUrl);
+            if (!Directory.Exists(dir))
+                Directory.CreateDirectory(dir);
+
+            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
+            Image initImage = Image.FromStream(fromFile, true);
+
+            //原图宽高均小于模版,不作处理,直接保存
+            if ((initImage.Width <= side) && (initImage.Height <= side))
+            {
+                initImage.Save(fileSaveUrl, ImageFormat.Jpeg);
+            }
+            else
+            {
+                //原始图片的宽、高
+                int initWidth = initImage.Width;
+                int initHeight = initImage.Height;
+
+                //非正方型先裁剪为正方型
+                if (initWidth != initHeight)
+                {
+                    //截图对象
+                    Image pickedImage = null;
+                    Graphics pickedG = null;
+
+                    //宽大于高的横图
+                    if (initWidth > initHeight)
+                    {
+                        //对象实例化
+                        pickedImage = new Bitmap(initHeight, initHeight);
+                        pickedG = Graphics.FromImage(pickedImage);
+                        //设置质量
+                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                        pickedG.SmoothingMode = SmoothingMode.HighQuality;
+                        //定位
+                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
+                        Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
+                        //画图
+                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
+                        //重置宽
+                        initWidth = initHeight;
+                    }
+                    //高大于宽的竖图
+                    else
+                    {
+                        //对象实例化
+                        pickedImage = new Bitmap(initWidth, initWidth);
+                        pickedG = Graphics.FromImage(pickedImage);
+                        //设置质量
+                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                        pickedG.SmoothingMode = SmoothingMode.HighQuality;
+                        //定位
+                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
+                        Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
+                        //画图
+                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
+                        //重置高
+                        initHeight = initWidth;
+                    }
+
+                    //将截图对象赋给原图
+                    initImage = (Image)pickedImage.Clone();
+                    //释放截图资源
+                    pickedG.Dispose();
+                    pickedImage.Dispose();
+                }
+
+                //缩略图对象
+                Image resultImage = new Bitmap(side, side);
+                Graphics resultG = Graphics.FromImage(resultImage);
+                //设置质量
+                resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                resultG.SmoothingMode = SmoothingMode.HighQuality;
+                //用指定背景色清空画布
+                resultG.Clear(Color.White);
+                //绘制缩略图
+                resultG.DrawImage(initImage, new Rectangle(0, 0, side, side), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);
+
+                //关键质量控制
+                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
+                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
+                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"))
+                        ici = i;
+                }
+                EncoderParameters ep = new EncoderParameters(1);
+                ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
+                //保存缩略图
+                resultImage.Save(fileSaveUrl, ici, ep);
+                //释放关键质量控制所用资源
+                ep.Dispose();
+                //释放缩略图资源
+                resultG.Dispose();
+                resultImage.Dispose();
+                //释放原始图片资源
+                initImage.Dispose();
+            }
+        }
+
+        #endregion
+
+        #region 自定义裁剪并缩放
+
+        /// <summary>
+        /// 指定长宽裁剪
+        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
+        /// </summary>
+        /// <param name="fromFile">原图Stream对象</param>
+        /// <param name="fileSaveUrl">保存路径</param>
+        /// <param name="maxWidth">最大宽(单位:px)</param>
+        /// <param name="maxHeight">最大高(单位:px)</param>
+        /// <param name="quality">质量(范围0-100)</param>
+        public static void CutForCustom(Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
+        {
+            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
+            Image initImage = Image.FromStream(fromFile, true);
+
+            //原图宽高均小于模版,不作处理,直接保存
+            if ((initImage.Width <= maxWidth) && (initImage.Height <= maxHeight))
+            {
+                initImage.Save(fileSaveUrl, ImageFormat.Jpeg);
+            }
+            else
+            {
+                //模版的宽高比例
+                double templateRate = (double)maxWidth / maxHeight;
+                //原图片的宽高比例
+                double initRate = (double)initImage.Width / initImage.Height;
+
+                //原图与模版比例相等,直接缩放
+                if (templateRate == initRate)
+                {
+                    //按模版大小生成最终图片
+                    Image templateImage = new Bitmap(maxWidth, maxHeight);
+                    Graphics templateG = Graphics.FromImage(templateImage);
+                    templateG.InterpolationMode = InterpolationMode.High;
+                    templateG.SmoothingMode = SmoothingMode.HighQuality;
+                    templateG.Clear(Color.White);
+                    templateG.DrawImage(initImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
+                    templateImage.Save(fileSaveUrl, ImageFormat.Jpeg);
+                }
+                //原图与模版比例不等,裁剪后缩放
+                else
+                {
+                    //裁剪对象
+                    Image pickedImage = null;
+                    Graphics pickedG = null;
+
+                    //定位
+                    Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
+                    Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位
+
+                    //宽为标准进行裁剪
+                    if (templateRate > initRate)
+                    {
+                        //裁剪对象实例化
+                        pickedImage = new Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate));
+                        pickedG = Graphics.FromImage(pickedImage);
+
+                        //裁剪源定位
+                        fromR.X = 0;
+                        fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
+                        fromR.Width = initImage.Width;
+                        fromR.Height = (int)Math.Floor(initImage.Width / templateRate);
+
+                        //裁剪目标定位
+                        toR.X = 0;
+                        toR.Y = 0;
+                        toR.Width = initImage.Width;
+                        toR.Height = (int)Math.Floor(initImage.Width / templateRate);
+                    }
+                    //高为标准进行裁剪
+                    else
+                    {
+                        pickedImage = new Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height);
+                        pickedG = Graphics.FromImage(pickedImage);
+
+                        fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
+                        fromR.Y = 0;
+                        fromR.Width = (int)Math.Floor(initImage.Height * templateRate);
+                        fromR.Height = initImage.Height;
+
+                        toR.X = 0;
+                        toR.Y = 0;
+                        toR.Width = (int)Math.Floor(initImage.Height * templateRate);
+                        toR.Height = initImage.Height;
+                    }
+
+                    //设置质量
+                    pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                    pickedG.SmoothingMode = SmoothingMode.HighQuality;
+
+                    //裁剪
+                    pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
+
+                    //按模版大小生成最终图片
+                    Image templateImage = new Bitmap(maxWidth, maxHeight);
+                    Graphics templateG = Graphics.FromImage(templateImage);
+                    templateG.InterpolationMode = InterpolationMode.High;
+                    templateG.SmoothingMode = SmoothingMode.HighQuality;
+                    templateG.Clear(Color.White);
+                    templateG.DrawImage(pickedImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, pickedImage.Width, pickedImage.Height), GraphicsUnit.Pixel);
+
+                    //关键质量控制
+                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
+                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
+                    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"))
+                            ici = i;
+                    }
+
+                    EncoderParameters ep = new EncoderParameters(1);
+                    ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
+
+                    //保存缩略图
+                    templateImage.Save(fileSaveUrl, ici, ep);
+                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
+
+                    //释放资源
+                    templateG.Dispose();
+                    templateImage.Dispose();
+
+                    pickedG.Dispose();
+                    pickedImage.Dispose();
+                }
+            }
+
+            //释放资源
+            initImage.Dispose();
+        }
+
+        #endregion
+
+        #region 等比缩放
+
+        /// <summary>
+        /// 图片等比缩放
+        /// </summary>
+        /// <param name="fromFile">原图Stream对象</param>
+        /// <param name="savePath">缩略图存放地址</param>
+        /// <param name="targetWidth">指定的最大宽度</param>
+        /// <param name="targetHeight">指定的最大高度</param>
+        /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
+        /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
+        public static void ZoomAuto(Stream fromFile, string savePath, double targetWidth, double targetHeight, string watermarkText, string watermarkImage)
+        {
+            //创建目录
+            string dir = Path.GetDirectoryName(savePath);
+            if (!Directory.Exists(dir))
+                Directory.CreateDirectory(dir);
+
+            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
+            Image initImage = Image.FromStream(fromFile, true);
+
+            //原图宽高均小于模版,不作处理,直接保存
+            if ((initImage.Width <= targetWidth) && (initImage.Height <= targetHeight))
+            {
+                //文字水印
+                if (watermarkText != "")
+                {
+                    using (Graphics gWater = Graphics.FromImage(initImage))
+                    {
+                        Font fontWater = new Font("黑体", 10);
+                        Brush brushWater = new SolidBrush(Color.White);
+                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
+                        gWater.Dispose();
+                    }
+                }
+
+                //透明图片水印
+                if (watermarkImage != "")
+                {
+                    if (File.Exists(watermarkImage))
+                    {
+                        using (Image wrImage = Image.FromFile(watermarkImage))
+                        {
+                            //水印绘制条件:原始图片宽高均大于或等于水印图片
+                            if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
+                            {
+                                Graphics gWater = Graphics.FromImage(initImage);
+
+                                //透明属性
+                                ImageAttributes imgAttributes = new ImageAttributes();
+                                ColorMap colorMap = new ColorMap();
+                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
+                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
+                                ColorMap[] remapTable = { colorMap };
+                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
+
+                                float[][] colorMatrixElements =
+                                {
+                                    new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                    new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
+                                    new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
+                                    new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
+                                    new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
+                                };
+
+                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
+                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
+                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
+
+                                gWater.Dispose();
+                            }
+                            wrImage.Dispose();
+                        }
+                    }
+                }
+
+                //保存
+                initImage.Save(savePath, ImageFormat.Jpeg);
+            }
+            else
+            {
+                //缩略图宽、高计算
+                double newWidth = initImage.Width;
+                double newHeight = initImage.Height;
+
+                //宽大于高或宽等于高(横图或正方)
+                if ((initImage.Width > initImage.Height) || (initImage.Width == initImage.Height))
+                {
+                    //如果宽大于模版
+                    if (initImage.Width > targetWidth)
+                    {
+                        //宽按模版,高按比例缩放
+                        newWidth = targetWidth;
+                        newHeight = initImage.Height * (targetWidth / initImage.Width);
+                    }
+                }
+                //高大于宽(竖图)
+                else
+                {
+                    //如果高大于模版
+                    if (initImage.Height > targetHeight)
+                    {
+                        //高按模版,宽按比例缩放
+                        newHeight = targetHeight;
+                        newWidth = initImage.Width * (targetHeight / initImage.Height);
+                    }
+                }
+
+                //生成新图
+                //新建一个bmp图片
+                Image newImage = new Bitmap((int)newWidth, (int)newHeight);
+                //新建一个画板
+                Graphics newG = Graphics.FromImage(newImage);
+
+                //设置质量
+                newG.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                newG.SmoothingMode = SmoothingMode.HighQuality;
+
+                //置背景色
+                newG.Clear(Color.White);
+                //画图
+                newG.DrawImage(initImage, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
+
+                //文字水印
+                if (watermarkText != "")
+                {
+                    using (Graphics gWater = Graphics.FromImage(newImage))
+                    {
+                        Font fontWater = new Font("宋体", 10);
+                        Brush brushWater = new SolidBrush(Color.White);
+                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
+                        gWater.Dispose();
+                    }
+                }
+
+                //透明图片水印
+                if (watermarkImage != "")
+                {
+                    if (File.Exists(watermarkImage))
+                    {
+                        using (Image wrImage = Image.FromFile(watermarkImage))
+                        {
+                            //水印绘制条件:原始图片宽高均大于或等于水印图片
+                            if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
+                            {
+                                Graphics gWater = Graphics.FromImage(newImage);
+
+                                //透明属性
+                                ImageAttributes imgAttributes = new ImageAttributes();
+                                ColorMap colorMap = new ColorMap();
+                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
+                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
+                                ColorMap[] remapTable = { colorMap };
+                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
+
+                                float[][] colorMatrixElements =
+                                {
+                                    new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                    new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
+                                    new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
+                                    new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
+                                    new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
+                                };
+
+                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
+                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
+                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
+                                gWater.Dispose();
+                            }
+                            wrImage.Dispose();
+                        }
+                    }
+                }
+
+                //保存缩略图
+                newImage.Save(savePath, ImageFormat.Jpeg);
+
+                //释放资源
+                newG.Dispose();
+                newImage.Dispose();
+                initImage.Dispose();
+            }
+        }
+
+        #endregion
+
+        #region 判断文件类型是否为WEB格式图片
+
+        /// <summary>
+        /// 判断文件类型是否为WEB格式图片
+        /// (注:JPG,GIF,BMP,PNG)
+        /// </summary>
+        /// <param name="contentType">HttpPostedFile.ContentType</param>
+        /// <returns></returns>
+        public static bool IsWebImage(string contentType)
+        {
+            if ((contentType == "image/pjpeg") || (contentType == "image/jpeg") || (contentType == "image/gif") || (contentType == "image/bmp") || (contentType == "image/png"))
+                return true;
+            return false;
+        }
+
+        #endregion
+
+        #region 裁剪图片
+
+        /// <summary>
+        /// 裁剪图片 -- 用GDI+   
+        /// </summary>
+        /// <param name="b">原始Bitmap</param>
+        /// <param name="rec">裁剪区域</param>
+        /// <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)
+                rec.Height = h - rec.Y;
+            try
+            {
+                Bitmap bmpOut = new Bitmap(rec.Width, rec.Height, PixelFormat.Format24bppRgb);
+                Graphics g = Graphics.FromImage(bmpOut);
+                g.DrawImage(b, new Rectangle(0, 0, rec.Width, rec.Height), new Rectangle(rec.X, rec.Y, rec.Width, rec.Height), GraphicsUnit.Pixel);
+                g.Dispose();
+                return bmpOut;
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        #endregion
+
+        #region 缩放图片
+
+        /// <summary>  
+        ///  Resize图片   
+        /// </summary>  
+        /// <param name="bmp">原始Bitmap </param>  
+        /// <param name="newWidth">新的宽度</param>  
+        /// <param name="newHeight">新的高度</param>  
+        /// <returns>处理以后的图片</returns>  
+        public static Bitmap ResizeImage(this Bitmap bmp, int newWidth, int newHeight)
+        {
+            try
+            {
+                Bitmap b = new Bitmap(newWidth, newHeight);
+                Graphics g = Graphics.FromImage(b);
+                // 插值算法的质量   
+                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                g.DrawImage(bmp, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
+                g.Dispose();
+                return b;
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        #endregion
+
+        #region 裁剪并缩放
+
+        /// <summary>
+        /// 裁剪并缩放
+        /// </summary>
+        /// <param name="bmp">原始图片</param>
+        /// <param name="rec">裁剪的矩形区域</param>
+        /// <param name="newWidth">新的宽度</param>  
+        /// <param name="newHeight">新的高度</param>  
+        /// <returns>处理以后的图片</returns>
+        public static Bitmap CutAndResize(this Bitmap bmp, Rectangle rec, int newWidth, int newHeight) => bmp.CutImage(rec).ResizeImage(newWidth, newHeight);
+
+        #endregion
+
+        #region 无损压缩图片
+
+        /// <summary>
+        /// 无损压缩图片
+        /// </summary>
+        /// <param name="sFile">原图片</param>
+        /// <param name="dFile">压缩后保存位置</param>
+        /// <param name="dHeight">高度</param>
+        /// <param name="dWidth"></param>
+        /// <param name="flag">压缩质量 1-100</param>
+        /// <returns></returns>
+        public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag = 100)
+        {
+            using (Image iSource = Image.FromFile(sFile))
+            {
+                ImageFormat tFormat = iSource.RawFormat;
+                int sW = 0, sH = 0;
+                //按比例缩放
+                Size tem_size = new Size(iSource.Width, iSource.Height);
+                if ((tem_size.Width > dHeight) || (tem_size.Width > dWidth)) //将**改成c#中的或者操作符号
+                {
+                    if (tem_size.Width * dHeight > tem_size.Height * dWidth)
+                    {
+                        sW = dWidth;
+                        sH = dWidth * tem_size.Height / tem_size.Width;
+                    }
+                    else
+                    {
+                        sH = dHeight;
+                        sW = tem_size.Width * dHeight / tem_size.Height;
+                    }
+                }
+                else
+                {
+                    sW = tem_size.Width;
+                    sH = tem_size.Height;
+                }
+                using (Bitmap ob = new Bitmap(dWidth, dHeight))
+                {
+                    Graphics g = Graphics.FromImage(ob);
+                    g.Clear(Color.WhiteSmoke);
+                    g.CompositingQuality = CompositingQuality.HighQuality;
+                    g.SmoothingMode = SmoothingMode.HighQuality;
+                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                    g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
+                    g.Dispose();
+                    //以下代码为保存图片时,设置压缩质量
+                    EncoderParameters ep = new EncoderParameters();
+                    long[] qy = new long[1];
+                    qy[0] = flag; //设置压缩的比例1-100
+                    EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
+                    ep.Param[0] = eParam;
+                    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
+                    ImageCodecInfo jpegICIinfo = null;
+                    for (int x = 0; x < arrayICI.Length; x++)
+                    {
+                        if (arrayICI[x].FormatDescription.Equals("JPEG"))
+                        {
+                            jpegICIinfo = arrayICI[x];
+                            break;
+                        }
+                    }
+
+                    if (jpegICIinfo != null)
+                        ob.Save(dFile, jpegICIinfo, ep); //dFile是压缩后的新路径
+                    else
+                        ob.Save(dFile, tFormat);
+                    return true;
+                }
+            }
+        }
+
+        #endregion
+
+        #region 缩略图
+
+        /// <summary>
+        /// 生成缩略图
+        /// </summary>
+        /// <param name="originalImagePath">源图路径(物理路径)</param>
+        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
+        /// <param name="width">缩略图宽度</param>
+        /// <param name="height">缩略图高度</param>
+        /// <param name="mode">生成缩略图的方式</param>    
+        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
+        {
+            Image originalImage = Image.FromFile(originalImagePath);
+
+            int towidth = width;
+            int toheight = height;
+
+            int x = 0;
+            int y = 0;
+            int ow = originalImage.Width;
+            int oh = originalImage.Height;
+
+            switch (mode)
+            {
+                case "HW": //指定高宽缩放(可能变形)                
+                    break;
+                case "W": //指定宽,高按比例                    
+                    toheight = originalImage.Height * width / originalImage.Width;
+                    break;
+                case "H": //指定高,宽按比例
+                    towidth = originalImage.Width * height / originalImage.Height;
+                    break;
+                case "Cut": //指定高宽裁减(不变形)                
+                    if (originalImage.Width / (double)originalImage.Height > towidth / (double)toheight)
+                    {
+                        oh = originalImage.Height;
+                        ow = originalImage.Height * towidth / toheight;
+                        y = 0;
+                        x = (originalImage.Width - ow) / 2;
+                    }
+                    else
+                    {
+                        ow = originalImage.Width;
+                        oh = originalImage.Width * height / towidth;
+                        x = 0;
+                        y = (originalImage.Height - oh) / 2;
+                    }
+                    break;
+                default:
+                    break;
+            }
+
+            //新建一个bmp图片
+            Image bitmap = new Bitmap(towidth, toheight);
+
+            //新建一个画板
+            Graphics g = Graphics.FromImage(bitmap);
+
+            //设置高质量插值法
+            g.InterpolationMode = InterpolationMode.High;
+
+            //设置高质量,低速度呈现平滑程度
+            g.SmoothingMode = SmoothingMode.HighQuality;
+
+            //清空画布并以透明背景色填充
+            g.Clear(Color.Transparent);
+
+            //在指定位置并且按指定大小绘制原图片的指定部分
+            //第一个:对哪张图片进行操作。
+            //二:画多么大。
+            //三:画那块区域。
+            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
+
+            try
+            {
+                //以jpg格式保存缩略图
+                bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
+            }
+            finally
+            {
+                originalImage.Dispose();
+                bitmap.Dispose();
+                g.Dispose();
+            }
+        }
+
+        #endregion
+
+        #region 调整光暗
+
+        /// <summary>
+        /// 调整光暗
+        /// </summary>
+        /// <param name="mybm">原始图片</param>
+        /// <param name="width">原始图片的长度</param>
+        /// <param name="height">原始图片的高度</param>
+        /// <param name="val">增加或减少的光暗值</param>
+        public static Bitmap LDPic(this Bitmap mybm, int width, int height, int val)
+        {
+            Bitmap bm = new Bitmap(width, height); //初始化一个记录经过处理后的图片对象
+            int x, y, resultR, resultG, resultB; //x、y是循环次数,后面三个是记录红绿蓝三个值的
+            Color pixel;
+            for (x = 0; x < width; x++)
+            {
+                for (y = 0; y < height; y++)
+                {
+                    pixel = mybm.GetPixel(x, y); //获取当前像素的值
+                    resultR = pixel.R + val; //检查红色值会不会超出[0, 255]
+                    resultG = pixel.G + val; //检查绿色值会不会超出[0, 255]
+                    resultB = pixel.B + val; //检查蓝色值会不会超出[0, 255]
+                    bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB)); //绘图
+                }
+            }
+
+            return bm;
+        }
+
+        #endregion
+
+        #region 反色处理
+
+        /// <summary>
+        /// 反色处理
+        /// </summary>
+        /// <param name="mybm">原始图片</param>
+        /// <param name="width">原始图片的长度</param>
+        /// <param name="height">原始图片的高度</param>
+        public static Bitmap RePic(this Bitmap mybm, int width, int height)
+        {
+            Bitmap bm = new Bitmap(width, height); //初始化一个记录处理后的图片的对象
+            int x, y, resultR, resultG, resultB;
+            Color pixel;
+            for (x = 0; x < width; x++)
+            {
+                for (y = 0; y < height; y++)
+                {
+                    pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
+                    resultR = 255 - pixel.R; //反红
+                    resultG = 255 - pixel.G; //反绿
+                    resultB = 255 - pixel.B; //反蓝
+                    bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB)); //绘图
+                }
+            }
+
+            return bm;
+        }
+
+        #endregion
+
+        #region 浮雕处理
+
+        /// <summary>
+        /// 浮雕处理
+        /// </summary>
+        /// <param name="oldBitmap">原始图片</param>
+        /// <param name="Width">原始图片的长度</param>
+        /// <param name="Height">原始图片的高度</param>
+        public static Bitmap Relief(this Bitmap oldBitmap, int Width, int Height)
+        {
+            Bitmap newBitmap = new Bitmap(Width, Height);
+            Color color1, color2;
+            for (int x = 0; x < Width - 1; x++)
+            {
+                for (int y = 0; y < Height - 1; y++)
+                {
+                    int r = 0, g = 0, b = 0;
+                    color1 = oldBitmap.GetPixel(x, y);
+                    color2 = oldBitmap.GetPixel(x + 1, y + 1);
+                    r = Math.Abs(color1.R - color2.R + 128);
+                    g = Math.Abs(color1.G - color2.G + 128);
+                    b = Math.Abs(color1.B - color2.B + 128);
+                    if (r > 255) r = 255;
+                    if (r < 0) r = 0;
+                    if (g > 255) g = 255;
+                    if (g < 0) g = 0;
+                    if (b > 255) b = 255;
+                    if (b < 0) b = 0;
+                    newBitmap.SetPixel(x, y, Color.FromArgb(r, g, b));
+                }
+            }
+
+            return newBitmap;
+        }
+
+        #endregion
+
+        #region 拉伸图片
+
+        /// <summary>
+        /// 拉伸图片
+        /// </summary>
+        /// <param name="bmp">原始图片</param>
+        /// <param name="newW">新的宽度</param>
+        /// <param name="newH">新的高度</param>
+        public static async Task<Bitmap> ResizeImageAsync(this Bitmap bmp, int newW, int newH)
+        {
+            try
+            {
+                using (Bitmap bap = new Bitmap(newW, newH))
+                {
+                    return await Task.Run(() =>
+                    {
+                        using (Graphics g = Graphics.FromImage(bap))
+                        {
+                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                            g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
+                        }
+                        return bap;
+                    }).ConfigureAwait(false);
+                }
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        #endregion
+
+        #region 滤色处理
+
+        /// <summary>
+        /// 滤色处理
+        /// </summary>
+        /// <param name="mybm">原始图片</param>
+        /// <param name="width">原始图片的长度</param>
+        /// <param name="height">原始图片的高度</param>
+        public static Bitmap FilPic(this Bitmap mybm, int width, int height)
+        {
+            using (Bitmap bm = new Bitmap(width, height)) //初始化一个记录滤色效果的图片对象
+            {
+                int x, y;
+                Color pixel;
+                for (x = 0; x < width; x++)
+                {
+                    for (y = 0; y < height; y++)
+                    {
+                        pixel = mybm.GetPixel(x, y); //获取当前坐标的像素值
+                        bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
+                    }
+                }
+
+                return bm;
+            }
+        }
+
+        #endregion
+
+        #region 左右翻转
+
+        /// <summary>
+        /// 左右翻转
+        /// </summary>
+        /// <param name="mybm">原始图片</param>
+        /// <param name="width">原始图片的长度</param>
+        /// <param name="height">原始图片的高度</param>
+        public static Bitmap RevPicLR(this Bitmap mybm, int width, int height)
+        {
+            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); //获取当前像素的值
+                        bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
+                    }
+                }
+
+                return bm;
+            }
+        }
+
+        #endregion
+
+        #region 上下翻转
+
+        /// <summary>
+        /// 上下翻转
+        /// </summary>
+        /// <param name="mybm">原始图片</param>
+        /// <param name="width">原始图片的长度</param>
+        /// <param name="height">原始图片的高度</param>
+        public static Bitmap RevPicUD(this Bitmap mybm, int width, int height)
+        {
+            Bitmap bm = new Bitmap(width, height);
+            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); //获取当前像素的值
+                        bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
+                    }
+                }
+
+                return bm;
+            }
+        }
+
+        #endregion
+
+        #region 压缩图片
+
+        /// <summary>
+        /// 压缩到指定尺寸
+        /// </summary>
+        /// <param name="oldfile">原文件</param>
+        /// <param name="newfile">新文件</param>
+        public static bool Compress(string oldfile, string newfile)
+        {
+            try
+            {
+                Image img = Image.FromFile(oldfile);
+                ImageFormat thisFormat = img.RawFormat;
+                Size newSize = new Size(100, 125);
+                Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
+                Graphics g = Graphics.FromImage(outBmp);
+                g.CompositingQuality = CompositingQuality.HighQuality;
+                g.SmoothingMode = SmoothingMode.HighQuality;
+                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+                g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
+                g.Dispose();
+                EncoderParameters encoderParams = new EncoderParameters();
+                long[] quality = new long[1];
+                quality[0] = 100;
+                EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
+                encoderParams.Param[0] = encoderParam;
+                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
+                ImageCodecInfo jpegICI = null;
+                for (int x = 0; x < arrayICI.Length; x++)
+                {
+                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
+                    {
+                        jpegICI = arrayICI[x]; //设置JPEG编码
+                        break;
+                    }
+                }
+
+                img.Dispose();
+                if (jpegICI != null) outBmp.Save(newfile, ImageFormat.Jpeg);
+                outBmp.Dispose();
+                return true;
+            }
+            catch
+            {
+                return false;
+            }
+        }
+
+        #endregion
+
+        #region 图片灰度化
+
+        /// <summary>
+        /// 图片灰度化
+        /// </summary>
+        /// <param name="c"></param>
+        /// <returns></returns>
+        public static Color Gray(Color c)
+        {
+            int rgb = Convert.ToInt32(0.3 * c.R + 0.59 * c.G + 0.11 * c.B);
+            return Color.FromArgb(rgb, rgb, rgb);
+        }
+
+        #endregion
+
+        #region 转换为黑白图片
+
+        /// <summary>
+        /// 转换为黑白图片
+        /// </summary>
+        /// <param name="mybm">要进行处理的图片</param>
+        /// <param name="width">图片的长度</param>
+        /// <param name="height">图片的高度</param>
+        public static Bitmap BWPic(this Bitmap mybm, int width, int height)
+        {
+            Bitmap bm = new Bitmap(width, height);
+            using (bm)
+            {
+                int x, y, result; //x,y是循环次数,result是记录处理后的像素值
+                Color pixel;
+                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; //取红绿蓝三色的平均值
+                        bm.SetPixel(x, y, Color.FromArgb(result, result, result));
+                    }
+                }
+
+                return bm;
+            }
+        }
+
+        #endregion
+
+        #region 获取图片中的各帧
+
+        /// <summary>
+        /// 获取图片中的各帧
+        /// </summary>
+        /// <param name="pPath">图片路径</param>
+        /// <param name="pSavedPath">保存路径</param>
+        public static void GetFrames(string pPath, string pSavedPath)
+        {
+            Image gif = Image.FromFile(pPath);
+            using (gif)
+            {
+                FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
+                int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
+                for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
+                {
+                    gif.SelectActiveFrame(fd, i);
+                    gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
+                }
+            }
+        }
+
+        #endregion
+
+        #region 图片水印
+
+        /// <summary>
+        /// 图片水印处理方法
+        /// </summary>
+        /// <param name="path">需要加载水印的图片路径(绝对路径)</param>
+        /// <param name="waterpath">水印图片(绝对路径)</param>
+        /// <param name="location">水印位置(传送正确的代码)</param>
+        public static string ImageWatermark(string path, string waterpath, string location)
+        {
+            string kz_name = Path.GetExtension(path);
+            if ((kz_name == ".jpg") || (kz_name == ".bmp") || (kz_name == ".jpeg"))
+            {
+                DateTime time = DateTime.Now;
+                string filename = "" + time.Year + time.Month + time.Day + time.Hour + time.Minute + time.Second + time.Millisecond;
+                Image img = Image.FromFile(path);
+                Image waterimg = Image.FromFile(waterpath);
+                Graphics g = Graphics.FromImage(img);
+                ArrayList loca = GetLocation(location, img, waterimg);
+                g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), waterimg.Width, waterimg.Height));
+                waterimg.Dispose();
+                g.Dispose();
+                string newpath = Path.GetDirectoryName(path) + filename + kz_name;
+                img.Save(newpath);
+                img.Dispose();
+                File.Copy(newpath, path, true);
+                if (File.Exists(newpath))
+                    File.Delete(newpath);
+            }
+            return path;
+        }
+
+        /// <summary>
+        /// 图片水印位置处理方法
+        /// </summary>
+        /// <param name="location">水印位置</param>
+        /// <param name="img">需要添加水印的图片</param>
+        /// <param name="waterimg">水印图片</param>
+        private static ArrayList GetLocation(string location, Image img, Image waterimg)
+        {
+            ArrayList loca = new ArrayList();
+            int x = 0;
+            int y = 0;
+
+            if (location == "LT")
+            {
+                x = 10;
+                y = 10;
+            }
+            else if (location == "T")
+            {
+                x = img.Width / 2 - waterimg.Width / 2;
+                y = img.Height - waterimg.Height;
+            }
+            else if (location == "RT")
+            {
+                x = img.Width - waterimg.Width;
+                y = 10;
+            }
+            else if (location == "LC")
+            {
+                x = 10;
+                y = img.Height / 2 - waterimg.Height / 2;
+            }
+            else if (location == "C")
+            {
+                x = img.Width / 2 - waterimg.Width / 2;
+                y = img.Height / 2 - waterimg.Height / 2;
+            }
+            else if (location == "RC")
+            {
+                x = img.Width - waterimg.Width;
+                y = img.Height / 2 - waterimg.Height / 2;
+            }
+            else if (location == "LB")
+            {
+                x = 10;
+                y = img.Height - waterimg.Height;
+            }
+            else if (location == "B")
+            {
+                x = img.Width / 2 - waterimg.Width / 2;
+                y = img.Height - waterimg.Height;
+            }
+            else
+            {
+                x = img.Width - waterimg.Width;
+                y = img.Height - waterimg.Height;
+            }
+            loca.Add(x);
+            loca.Add(y);
+            return loca;
+        }
+
+        #endregion
+
+        #region 文字水印
+
+        /// <summary>
+        /// 文字水印处理方法
+        /// </summary>
+        /// <param name="path">图片路径(绝对路径)</param>
+        /// <param name="size">字体大小</param>
+        /// <param name="letter">水印文字</param>
+        /// <param name="color">颜色</param>
+        /// <param name="location">水印位置</param>
+        public static string LetterWatermark(string path, int size, string letter, Color color, string location)
+        {
+            #region
+
+            string kz_name = Path.GetExtension(path);
+            if ((kz_name == ".jpg") || (kz_name == ".bmp") || (kz_name == ".jpeg"))
+            {
+                DateTime time = DateTime.Now;
+                string filename = "" + time.Year + time.Month + time.Day + time.Hour + time.Minute + time.Second + time.Millisecond;
+                Image img = Image.FromFile(path);
+                Graphics gs = Graphics.FromImage(img);
+                ArrayList loca = GetLocation(location, img, size, letter.Length);
+                Font font = new Font("宋体", size);
+                Brush br = new SolidBrush(color);
+                gs.DrawString(letter, font, br, float.Parse(loca[0].ToString()), float.Parse(loca[1].ToString()));
+                gs.Dispose();
+                string newpath = Path.GetDirectoryName(path) + filename + kz_name;
+                img.Save(newpath);
+                img.Dispose();
+                File.Copy(newpath, path, true);
+                if (File.Exists(newpath))
+                    File.Delete(newpath);
+            }
+            return path;
+
+            #endregion
+        }
+
+        /// <summary>
+        /// 文字水印位置的方法
+        /// </summary>
+        /// <param name="location">位置代码</param>
+        /// <param name="img">图片对象</param>
+        /// <param name="width">宽(当水印类型为文字时,传过来的就是字体的大小)</param>
+        /// <param name="height">高(当水印类型为文字时,传过来的就是字符的长度)</param>
+        private static ArrayList GetLocation(string location, Image img, int width, int height)
+        {
+            #region
+
+            ArrayList loca = new ArrayList(); //定义数组存储位置
+            float x = 10;
+            float y = 10;
+
+            if (location == "LT")
+            {
+                loca.Add(x);
+                loca.Add(y);
+            }
+            else if (location == "T")
+            {
+                x = img.Width / 2 - width * height / 2;
+                loca.Add(x);
+                loca.Add(y);
+            }
+            else if (location == "RT")
+            {
+                x = img.Width - width * height;
+            }
+            else if (location == "LC")
+            {
+                y = img.Height / 2;
+            }
+            else if (location == "C")
+            {
+                x = img.Width / 2 - width * height / 2;
+                y = img.Height / 2;
+            }
+            else if (location == "RC")
+            {
+                x = img.Width - height;
+                y = img.Height / 2;
+            }
+            else if (location == "LB")
+            {
+                y = img.Height - width - 5;
+            }
+            else if (location == "B")
+            {
+                x = img.Width / 2 - width * height / 2;
+                y = img.Height - width - 5;
+            }
+            else
+            {
+                x = img.Width - (width * height);
+                y = img.Height - width - 5;
+            }
+            loca.Add(x);
+            loca.Add(y);
+            return loca;
+
+            #endregion
+        }
+
+        #endregion
+    } //end class
+}

+ 176 - 0
Masuit.Tools/Models/AsposeLicense.cs

@@ -0,0 +1,176 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Xml;
+
+namespace Masuit.Tools.Models
+{
+    /// <summary>
+    /// Aspose内存补丁
+    /// </summary>
+    public static class AsposeLicense
+    {
+        private static readonly string AsposeList = "Aspose.3D.dll, Aspose.BarCode.dll, Aspose.BarCode.Compact.dll, Aspose.BarCode.WPF.dll, Aspose.Cells.GridDesktop.dll, Aspose.Cells.GridWeb.dll, Aspose.CAD.dll, Aspose.Cells.dll, Aspose.Diagram.dll, Aspose.Email.dll, Aspose.Imaging.dll, Aspose.Note.dll, Aspose.OCR.dll, Aspose.Pdf.dll, Aspose.Slides.dll, Aspose.Tasks.dll, Aspose.Words.dll";
+
+        /// <summary>
+        /// 启动Aspose的内存破解
+        /// </summary>
+        public static void ActivateMemoryPatching()
+        {
+            Assembly[] arr = AppDomain.CurrentDomain.GetAssemblies();
+            foreach (Assembly assembly in arr)
+            {
+                if (AsposeList.IndexOf(assembly.FullName.Split(',')[0] + ".dll") != -1)
+                    ActivateForAssembly(assembly);
+            }
+            AppDomain.CurrentDomain.AssemblyLoad += ActivateOnLoad;
+        }
+
+        private static void ActivateOnLoad(object sender, AssemblyLoadEventArgs e)
+        {
+            if (AsposeList.IndexOf(e.LoadedAssembly.FullName.Split(',')[0] + ".dll") != -1)
+                ActivateForAssembly(e.LoadedAssembly);
+        }
+
+        private static void ActivateForAssembly(Assembly assembly)
+        {
+            MethodInfo miLicensed1 = typeof(AsposeLicense).GetMethod("InvokeMe1", BindingFlags.NonPublic | BindingFlags.Static);
+            MethodInfo miLicensed2 = typeof(AsposeLicense).GetMethod("InvokeMe2", BindingFlags.NonPublic | BindingFlags.Static);
+            MethodInfo miEvaluation = null;
+
+            Dictionary<string, MethodInfo> miDict = new Dictionary<string, MethodInfo>
+            {
+                ["System.DateTime"] = miLicensed1,
+                ["System.Xml.XmlElement"] = miLicensed2
+            };
+
+            Type[] arrType = null;
+            bool isFound = false;
+            int nCount = 0;
+
+            try
+            {
+                arrType = assembly.GetTypes();
+            }
+            catch (ReflectionTypeLoadException err)
+            {
+                arrType = err.Types;
+            }
+            foreach (Type type in arrType)
+            {
+                if (isFound) break;
+                if (type == null) continue;
+                MethodInfo[] arrMInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);
+                foreach (MethodInfo info in arrMInfo)
+                {
+                    if (isFound) break;
+                    try
+                    {
+                        string strMethod = info.ToString();
+                        if ((strMethod.IndexOf("(System.Xml.XmlElement, System.String)") > 0) && miDict.ContainsKey(info.ReturnType.ToString()))
+                        {
+                            miEvaluation = info;
+                            MemoryPatching(miEvaluation, miDict[miEvaluation.ReturnType.ToString()]);
+                            nCount++;
+                            if (((assembly.FullName.IndexOf("Aspose.Pdf") == -1) && (nCount == 2)) || ((assembly.FullName.IndexOf("Aspose.Pdf") != -1) && (nCount == 6)))
+                            {
+                                isFound = true;
+                                break;
+                            }
+                        }
+                    }
+                    catch
+                    {
+                        throw new InvalidOperationException("MemoryPatching for \"" + assembly.FullName + "\" failed !");
+                    }
+                }
+            }
+
+            string[] aParts = assembly.FullName.Split(',');
+            string fName = aParts[0];
+            if (fName.IndexOf("Aspose.BarCode.") != -1)
+                fName = "Aspose.BarCode";
+            else if (fName.IndexOf("Aspose.3D") != -1)
+                fName = "Aspose.ThreeD";
+
+            try
+            {
+                Type type2 = assembly.GetType(fName + ".License");
+                MethodInfo mi = type2.GetMethod("SetLicense", new[] { typeof(Stream) });
+                const string LData = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5MaWNlbnNlZTwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPmxpY2Vuc2VlQGVtYWlsLmNvbTwvRW1haWxUbz4KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4KICAgIDxMaWNlbnNlTm90ZT5MaW1pdGVkIHRvIDEwMDAgZGV2ZWxvcGVyLCB1bmxpbWl0ZWQgcGh5c2ljYWwgbG9jYXRpb25zPC9MaWNlbnNlTm90ZT4KICAgIDxPcmRlcklEPjc4NDM3ODU3Nzg1PC9PcmRlcklEPgogICAgPFVzZXJJRD4xMTk3ODkyNDM3OTwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIFByb2R1Y3QgRmFtaWx5PC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+e0YyQjk3MDQ1LTFCMjktNEIzRi1CRDUzLTYwMUVGRkExNUFBOX08L1NlcmlhbE51bWJlcj4KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+MjA5OTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4KICAgIDxMaWNlbnNlVmVyc2lvbj4zLjA8L0xpY2Vuc2VWZXJzaW9uPgogIDwvRGF0YT4KICA8U2lnbmF0dXJlPlFYTndiM05sTGxSdmRHRnNJRkJ5YjJSMVkzUWdSbUZ0YVd4NTwvU2lnbmF0dXJlPgo8L0xpY2Vuc2U+";
+                Stream stream = new MemoryStream(Convert.FromBase64String(LData));
+                stream.Seek(0, SeekOrigin.Begin);
+                mi.Invoke(Activator.CreateInstance(type2, null), new[] { stream });
+            }
+            catch
+            {
+                throw new InvalidOperationException("SetLicense for \"" + assembly.FullName + "\" failed !");
+            }
+        }
+
+        private static DateTime InvokeMe1(XmlElement element, string name)
+        {
+            return DateTime.MaxValue;
+        }
+
+        private static XmlElement InvokeMe2(XmlElement element, string name)
+        {
+            if (element.LocalName == "License")
+            {
+                const string License64 = "PERhdGE+PExpY2Vuc2VkVG8+R3JvdXBEb2NzPC9MaWNlbnNlZFRvPjxMaWNlbnNlVHlwZT5TaXRlIE9FTTwvTGljZW5zZVR5cGU+PExpY2Vuc2VOb3RlPkxpbWl0ZWQgdG8gMTAgZGV2ZWxvcGVyczwvTGljZW5zZU5vdGU+PE9yZGVySUQ+MTMwNzI0MDQwODQ5PC9PcmRlcklEPjxPRU0+VGhpcyBpcyBhIHJlZGlzdHJpYnV0YWJsZSBsaWNlbnNlPC9PRU0+PFByb2R1Y3RzPjxQcm9kdWN0PkFzcG9zZS5Ub3RhbDwvUHJvZHVjdD48L1Byb2R1Y3RzPjxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT48U2VyaWFsTnVtYmVyPjliNTc5NTAxLTUyNjEtNDIyMC04NjcwLWZjMmQ4Y2NkZDkwYzwvU2VyaWFsTnVtYmVyPjxTdWJzY3JpcHRpb25FeHBpcnk+MjAxNDA3MjQ8L1N1YnNjcmlwdGlvbkV4cGlyeT48TGljZW5zZVZlcnNpb24+Mi4yPC9MaWNlbnNlVmVyc2lvbj48L0RhdGE+PFNpZ25hdHVyZT5udFpocmRoL3I0QS81ZFpsU2dWYnhac0hYSFBxSjZ5UVVYa0RvaW4vS2lVZWhUUWZET0lQdHdzUlR2NmRTUVplOVdXekNnV3RGdkdROWpmR2QySmF4YUQvbkx1ZEk2R0VVajhqeVhUMG4vbWRrMEF1WVZNYlBXRjJYd3dSTnFlTmRrblYyQjhrZVFwbDJ2RzZVbnhxS2J6VVFxS2Rhc1pzZ2w1Q0xqSFVEWms9PC9TaWduYXR1cmU+";
+                element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(License64));
+            }
+
+            if (element.LocalName == "BlackList")
+            {
+                const string BlackList64 = "PERhdGE+PC9EYXRhPjxTaWduYXR1cmU+cUJwMEx1cEVoM1ZnOWJjeS8vbUVXUk9KRWZmczRlY25iTHQxYlNhanU2NjY5RHlad09FakJ1eEdBdVBxS1hyd0x5bmZ5VWplYUNGQ0QxSkh2RVUxVUl5eXJOTnBSMXc2NXJIOUFyUCtFbE1lVCtIQkZ4NFMzckFVMnd6dkxPZnhGeU9DQ0dGQ2UraTdiSHlGQk44WHp6R1UwdGRPMGR1RTFoRTQ5M1RNY3pRPTwvU2lnbmF0dXJlPg==";
+                element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(BlackList64));
+            }
+
+            XmlNodeList elementsByTagName = element.GetElementsByTagName(name);
+            if (elementsByTagName.Count <= 0)
+                return null;
+
+            return (XmlElement)elementsByTagName[0];
+        }
+
+        private static unsafe void MemoryPatching(MethodBase miEvaluation, MethodBase miLicensed)
+        {
+            IntPtr IntPtrEval = GetMemoryAddress(miEvaluation);
+            IntPtr IntPtrLicensed = GetMemoryAddress(miLicensed);
+
+            if (IntPtr.Size == 8)
+                *(long*)IntPtrEval.ToPointer() = *(long*)IntPtrLicensed.ToPointer();
+            else
+                *(int*)IntPtrEval.ToPointer() = *(int*)IntPtrLicensed.ToPointer();
+        }
+
+        private static unsafe IntPtr GetMemoryAddress(MethodBase mb)
+        {
+            RuntimeHelpers.PrepareMethod(mb.MethodHandle);
+
+            if ((Environment.Version.Major >= 4) || ((Environment.Version.Major == 2) && (Environment.Version.MinorRevision >= 3053)))
+                return new IntPtr((int*)mb.MethodHandle.Value.ToPointer() + 2);
+
+            ulong* location = (ulong*)mb.MethodHandle.Value.ToPointer();
+            int index = (int)((*location >> 32) & 0xFF);
+            if (IntPtr.Size == 8)
+            {
+                ulong* classStart = (ulong*)mb.DeclaringType.TypeHandle.Value.ToPointer();
+                ulong* address = classStart + index + 10;
+                return new IntPtr(address);
+            }
+            else
+            {
+                uint* classStart = (uint*)mb.DeclaringType.TypeHandle.Value.ToPointer();
+                uint* address = classStart + index + 10;
+                return new IntPtr(address);
+            }
+        }
+    }
+}
+
+//End

+ 15 - 0
Masuit.Tools/Models/Email.cs

@@ -0,0 +1,15 @@
+namespace Masuit.Utilities.Models
+{
+#pragma warning disable 1591
+    public class Email
+    {
+        public string Subject { get; set; }
+        public string Body { get; set; }
+        public string MailAccount { get; set; }
+        public string Password { get; set; }
+        public string Smtp { get; set; }
+        public string To { get; set; }
+        public bool IsHtml { get; set; }
+    }
+#pragma warning restore 1591
+}

+ 10 - 0
Masuit.Tools/Models/INetAddress.cs

@@ -0,0 +1,10 @@
+namespace Masuit.Utilities.Models
+{
+#pragma warning disable 1591
+    public class INetAddress
+    {
+        public int code { get; set; } = 0;
+        public IPData data { get; set; } = new IPData();
+    }
+#pragma warning restore 1591
+}

+ 21 - 0
Masuit.Tools/Models/IPData.cs

@@ -0,0 +1,21 @@
+namespace Masuit.Utilities.Models
+{
+#pragma warning disable 1591
+    public class IPData
+    {
+        public string country { get; set; } = "中国";
+        public string country_id { get; set; } = "CN";
+        public string area { get; set; }
+        public string area_id { get; set; }
+        public string region { get; set; }
+        public string region_id { get; set; }
+        public string city { get; set; }
+        public string city_id { get; set; }
+        public string county { get; set; }
+        public string county_id { get; set; }
+        public string isp { get; set; }
+        public string isp_id { get; set; }
+        public string ip { get; set; }
+    }
+#pragma warning restore 1591
+}

+ 129 - 0
Masuit.Tools/Net/CacheHelper.cs

@@ -0,0 +1,129 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Web;
+using System.Web.Caching;
+
+namespace Masuit.Tools.Net
+{
+    /// <summary>
+    /// 全局统一的缓存类
+    /// </summary>
+    public static class CacheHelper
+    {
+        #region  获取数据缓存
+
+        /// <summary>
+        /// 获取数据缓存
+        /// </summary>
+        /// <typeparam name="T">返回的类型</typeparam>
+        /// <param name="CacheKey">键</param>
+        public static T GetCache<T>(string CacheKey)
+        {
+            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
+            return (T)objCache[CacheKey];
+        }
+        #endregion
+
+        #region  设置数据缓存
+
+        /// <summary>
+        /// 设置数据缓存
+        /// </summary>
+        /// <param name="CacheKey">键</param>
+        /// <param name="objObject">值</param>
+        public static void SetCache(string CacheKey, object objObject)
+        {
+            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
+            objCache.Insert(CacheKey, objObject);
+        }
+
+        /// <summary>
+        /// 设置数据缓存
+        /// </summary>
+        /// <param name="cacheKey">键</param>
+        /// <param name="objObject">值</param>
+        /// <param name="Timeout">过期时间</param>
+        /// <exception cref="ArgumentNullException"><paramref name="cacheKey"/>"/> is <c>null</c>.</exception>
+        public static void SetCache(string cacheKey, object objObject, TimeSpan Timeout)
+        {
+            if (cacheKey == null) throw new ArgumentNullException(nameof(cacheKey));
+            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
+            objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
+        }
+
+        /// <summary>
+        /// 设置当前应用程序指定CacheKey的Cache值
+        /// </summary>
+        /// <param name="CacheKey">键</param>
+        /// <param name="objObject">值</param>
+        /// <param name="absoluteExpiration">绝对过期时间</param>
+        /// <param name="slidingExpiration">滑动过期时间</param>
+        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
+        {
+            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
+            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
+        }
+        #endregion
+
+        #region   移除缓存
+        /// <summary>
+        /// 移除指定数据缓存
+        /// </summary>
+        /// <param name="CacheKey">键</param>
+        public static void RemoveAllCache(string CacheKey)
+        {
+            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
+            _cache.Remove(CacheKey);
+        }
+
+        /// <summary>
+        /// 移除全部缓存
+        /// </summary>
+        public static void RemoveAllCache()
+        {
+            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
+            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
+            while (CacheEnum.MoveNext())
+            {
+                _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();
+
+        /// <summary>
+        /// 添加缓存数据
+        /// </summary>
+        /// <param name="key">键</param>
+        /// <param name="value">值</param>
+        public static void Add(string key, object value)
+        {
+            dic.Add(key, value);
+        }
+
+        /// <summary>
+        /// 缓存实例
+        /// </summary>
+        public static Cache Instance
+        {
+            get
+            {
+                if (instance == null)
+                {
+                    lock (lockHelper)
+                    {
+                        if (instance == null)
+                        {
+                            instance = new Cache();
+                        }
+                    }
+                }
+                return instance;
+            }
+        }
+    }
+}

+ 507 - 0
Masuit.Tools/Net/CookieHelper.cs

@@ -0,0 +1,507 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Net;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using System.Web;
+
+namespace Masuit.Tools.Net
+{
+    /// <summary>
+    ///  Cookie操作辅助类
+    /// </summary>
+    public static class CookieHelper
+    {
+        /// <summary>
+        /// Win32API
+        /// </summary>
+        /// <param name="url"></param>
+        /// <param name="cookieName"></param>
+        /// <param name="cookieData"></param>
+        /// <param name="size"></param>
+        /// <returns></returns>
+        [DllImport("wininet.dll", SetLastError = true)]
+        public static extern bool InternetGetCookie(string url, string cookieName, StringBuilder cookieData, ref int size);
+
+        /// <summary>
+        /// 获取Cookie容器
+        /// </summary>
+        /// <param name="uri">URL</param>
+        /// <returns>Cookie容器</returns>
+        public static CookieContainer GetUriCookieContainer(Uri uri)
+        {
+            CookieContainer cookies = null;
+            //定义Cookie数据的大小。   
+            int datasize = 256;
+            StringBuilder cookieData = new StringBuilder(datasize);
+            if (!InternetGetCookie(uri.ToString(), null, cookieData, ref datasize))
+            {
+                if (datasize < 0) return null;
+                // 确信有足够大的空间来容纳Cookie数据。   
+                cookieData = new StringBuilder(datasize);
+                if (!InternetGetCookie(uri.ToString(), null, cookieData, ref datasize)) return null;
+            }
+            if (cookieData.Length > 0)
+            {
+                cookies = new CookieContainer();
+                cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
+            }
+            return cookies;
+        }
+
+        /// <summary>
+        /// 获取url下的Cookie
+        /// </summary>
+        /// <param name="cookies">Cookie对象</param>
+        /// <param name="uri">URL</param>
+        /// <returns>Cookie内容</returns>
+        public static string PrintCookies(CookieContainer cookies, Uri uri)
+        {
+            CookieCollection cc = cookies.GetCookies(uri);
+            StringBuilder sb = new StringBuilder();
+            foreach (Cookie cook in cc)
+            {
+                sb.AppendLine(string.Format("{0}:{1}", cook.Name, cook.Value));
+            }
+            return sb.ToString();
+        }
+
+        #region 清除CooKie 
+
+        #region 清除指定Cookie
+        /// <summary>
+        /// 清除指定Cookie
+        /// </summary>
+        /// <param name="cookiename">cookiename</param>
+        public static void ClearCookie(string cookiename)
+        {
+            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
+            if (cookie != null)
+            {
+                cookie.Expires = DateTime.Now.AddYears(-3);
+                HttpContext.Current.Response.Cookies.Add(cookie);
+            }
+        }
+        #endregion
+
+        #region   删除所有cookie值
+        /// <summary>
+        /// 删除所有cookie值
+        /// </summary>
+        public static void Clear()
+        {
+            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);
+            }
+        }
+        #endregion
+
+        #region 清除系统指定的Cookie
+        /// <summary>
+        /// 清除系统指定的Cookie
+        /// </summary>
+        /// <param name="ck">指定的Cookie</param>
+        /// <param name="url">Cookie的域</param>
+        public static void ClearCookies(string ck, string url)
+        {
+            string[] cks = GetCKS(ck);
+            List<string> domains = GetDomains(url);
+            for (int i = 0; i < cks.Length; i++)
+            {
+                string[] nv = cks[i].Split('=');
+                for (int j = 0; j < domains.Count; j++)
+                {
+                    InternetSetCookie(domains[j], nv[0], "abc;expires = Sat, 31-Dec-2007 14:00:00 GMT");
+                }
+            }
+        }
+        #endregion
+
+        #region 清除系统的Cookie文件
+
+        /// <summary>
+        /// 清除系统的Cookie文件
+        /// </summary>
+        public static void ClearCookiesFiles()
+        {
+            DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
+            foreach (FileInfo file in di.GetFiles())
+            {
+                try
+                {
+                    file.Delete();
+                }
+                catch
+                {
+                }
+            }
+        }
+        #endregion
+        #endregion
+
+        #region 获取Cookie
+
+        #region 获取指定Cookie值
+
+        /// <summary>
+        /// 获取指定Cookie值
+        /// </summary>
+        /// <param name="cookiename">cookiename</param>
+        /// <returns></returns>
+        public static string GetCookieValue(string cookiename)
+        {
+            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
+            string str = String.Empty;
+            if (cookie != null)
+            {
+                str = cookie.Value;
+            }
+            return str;
+        }
+
+        /// <summary>
+        /// 根据Key值得到Cookie值,Key不区分大小写
+        /// </summary>
+        /// <param name="Key">key</param>
+        /// <param name="cookie">字符串Cookie</param>
+        /// <returns></returns>
+        public static string GetCookieValue(string Key, string cookie)
+        {
+            foreach (CookieItem item in GetCookieList(cookie))
+            {
+                if (item.Key == Key)
+                    return item.Value;
+            }
+            return "";
+        }
+
+        /// <summary>
+        /// 根据字符生成Cookie列表
+        /// </summary>
+        /// <param name="cookie">Cookie字符串</param>
+        /// <returns></returns>
+        public static List<CookieItem> GetCookieList(string cookie)
+        {
+            List<CookieItem> cookielist = new List<CookieItem>();
+            foreach (string item in cookie.Split(new string[] { ";", "," }, 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 });
+                }
+            }
+            return cookielist;
+        }
+        #endregion
+
+        #region  获取cookie数组
+
+        /// <summary>
+        /// 获取cookie数组
+        /// </summary>
+        /// <param name="ck"></param>
+        /// <returns></returns>
+        public static string[] GetCKS(string ck)
+        {
+            if (ck != null)
+            {
+                return ck.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
+            }
+            else
+            {
+                return new string[0];
+            }
+        }
+        #endregion
+
+        #region  从Cookie数组中转换成不重复的Cookie字符串,相同的Cookie取前面的
+
+        /// <summary>
+        /// 从Cookie数组中转换成不重复的Cookie字符串,相同的Cookie取前面的
+        /// </summary>
+        /// <param name="cks">Cookie数组</param>
+        /// <returns>剔除重复的Cookie字符串</returns>
+        public static string GetCK(string[] cks)
+        {
+            string res = "";
+            List<string> list = new List<string>();
+            for (int i = 0; i < cks.Length; i++)
+            {
+                if (cks[i].Trim() != "")
+                {
+                    if (!IncludeCKAsync(list, cks[i]).Result)
+                    {
+                        list.Add(cks[i].Trim());
+                    }
+                }
+            }
+            for (int i = 0; i < list.Count; i++)
+            {
+                res += list[i] + ";";
+            }
+            return res;
+        }
+        #endregion
+
+        #region  从CookieCollection中获取Cookie字符串
+
+        /// <summary>
+        /// 从CookieCollection中获取Cookie字符串
+        /// </summary>
+        /// <param name="cc">CookieCollection,一般用在WebRequest中</param>
+        /// <returns>转换后的Cookie字符串</returns>
+        public static string GetCK(CookieCollection cc)
+        {
+            string ck = "";
+            for (int i = 0; i < cc.Count; i++)
+            {
+                ck += cc[i].Name + "=" + cc[i].Value + ";";
+            }
+            return ck;
+        }
+        #endregion
+
+        #region   将Cookie字符串填充到CookieCollection中
+
+        /// <summary>
+        /// 将Cookie字符串填充到CookieCollection中
+        /// </summary>
+        /// <param name="ck">Cookie字符串</param>
+        /// <param name="url">Cookie的域</param>
+        /// <returns>添加后的CookieCollection</returns>
+        public static CookieCollection GetCK(string ck, string url)
+        {
+            CookieCollection cc = new CookieCollection();
+            string domain = "";
+            try
+            {
+                Uri u = new Uri(url);
+                domain = u.Host;
+            }
+            catch
+            {
+            }
+            string[] cks = GetCKS(ck);
+            for (int i = 0; i < cks.Length; i++)
+            {
+                if (cks[i].IndexOf("=") > -1)
+                {
+                    try
+                    {
+                        string n = cks[i].Substring(0, cks[i].IndexOf("="));
+                        string v = cks[i].Substring(cks[i].IndexOf("=") + 1);
+                        System.Net.Cookie c = new System.Net.Cookie();
+                        c.Name = n.Trim();
+                        c.Value = v.Trim();
+                        c.Domain = domain;
+                        cc.Add(c);
+                    }
+                    catch
+                    {
+                    }
+                }
+            }
+            return cc;
+        }
+        #endregion
+        #endregion
+
+        #region 添加Cookie
+
+        #region   添加一个Cookie(24小时过期)
+
+        /// <summary>
+        /// 添加一个Cookie(24小时过期)
+        /// </summary>
+        /// <param name="cookiename"></param>
+        /// <param name="cookievalue"></param>
+        public static void SetCookie(string cookiename, string cookievalue)
+        {
+            SetCookie(cookiename, cookievalue, DateTime.Now.AddDays(1.0));
+        }
+        #endregion
+
+        #region   添加一个Cookie
+        /// <summary>
+        /// 添加一个Cookie
+        /// </summary>
+        /// <param name="cookiename">cookie名</param>
+        /// <param name="cookievalue">cookie值</param>
+        /// <param name="expires">过期时间 DateTime</param>
+        public static void SetCookie(string cookiename, string cookievalue, DateTime expires)
+        {
+            HttpCookie cookie = new HttpCookie(cookiename)
+            {
+                Value = cookievalue,
+                Expires = expires
+            };
+            HttpContext.Current.Response.Cookies.Add(cookie);
+        }
+        #endregion
+        #endregion
+
+        #region 检查Cookie集合中是否包含指定的Cookie值
+
+        /// <summary>
+        /// 检查Cookie集合中是否包含指定的Cookie值
+        /// </summary>
+        /// <param name="cks">Cookie集合</param>
+        /// <param name="ck">待判断的Cookie</param>
+        /// <returns>Cookie集合中是否包含指定的Cookie</returns>
+        public static async Task<bool> IncludeCKAsync(List<string> cks, string ck)
+        {
+            try
+            {
+                return await Task.Run(() =>
+                {
+                    foreach (string t in cks)
+                    {
+                        if (t.ToLower().Trim().IndexOf(ck.Remove(ck.IndexOf('=') + 1).Trim().ToLower(), StringComparison.Ordinal) != -1)
+                        {
+                            return true;
+                        }
+                    }
+                    return false;
+                }).ConfigureAwait(false);
+            }
+            catch { return false; }
+        }
+        #endregion
+
+        #region 设置系统Cookie
+
+        /// <summary>
+        /// 设置系统Cookie
+        /// </summary>
+        /// <param name="lpszUrlName">Cookie域</param>
+        /// <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)]
+        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
+        #endregion
+
+        #region   获取所有可能的Cookie域
+
+        /// <summary>
+        /// 获取所有可能的Cookie域
+        /// </summary>
+        /// <param name="url">域的全称</param>
+        /// <returns>所有可能的域</returns>
+        public static List<string> GetDomains(string url)
+        {
+            List<string> res = new List<string>();
+            try
+            {
+                url = url.Remove(url.IndexOf("?"));
+            }
+            catch
+            {
+            }
+            try
+            {
+                Uri uri = new Uri(url);
+                string baseDomain = uri.Scheme + "://" + uri.Host;
+                for (int i = 0; i < uri.Segments.Length; i++)
+                {
+                    baseDomain += uri.Segments[i];
+                    res.Add(baseDomain);
+                }
+            }
+            catch
+            {
+            }
+            return res;
+        }
+        #endregion
+
+        #region  将Cookie字符串描述的Cookie追加到CookieCoollection
+
+        /// <summary>
+        /// 将Cookie字符串描述的Cookie追加到CookieCoollection
+        /// </summary>
+        /// <param name="cc">CookieCoollection</param>
+        /// <param name="ck">Cookie字符串</param>
+        /// <param name="url">Cookie的域</param>
+        public static void SetCKAppendToCC(CookieCollection cc, string ck, string url)
+        {
+            CookieCollection tmp = GetCK(ck, url);
+            for (int i = 0; i < tmp.Count; i++)
+            {
+                cc.Add(tmp[i]);
+            }
+        }
+        #endregion
+
+        #region 将Cookie字符串设置到系统中,便于浏览器使用
+
+        /// <summary>
+        /// 将Cookie字符串设置到系统中,便于浏览器使用
+        /// </summary>
+        /// <param name="ck">Cookie字符串</param>
+        /// <param name="url">Cookie的域</param>
+        public static void SetCKToSystem(string ck, string url)
+        {
+            string[] cks = GetCKS(ck);
+            for (int i = 0; i < cks.Length; i++)
+            {
+                string[] nv = cks[i].Split('=');
+                InternetSetCookie(url, nv[0], nv.Length > 1 ? nv[1] : "");
+            }
+        }
+        #endregion
+
+        #region 将CookieCollection中的Cookie设置到系统中,便于浏览器使用
+        /// <summary>
+        /// 将CookieCollection中的Cookie设置到系统中,便于浏览器使用
+        /// </summary>
+        /// <param name="cc">CookieCollection</param>
+        /// <param name="url">Cookie的域</param>
+        public static void SetCKToSystem(CookieCollection cc, string url)
+        {
+            List<string> domains = GetDomains(url);
+            for (int i = 0; i < cc.Count; i++)
+            {
+                for (int j = 0; j < domains.Count; j++)
+                {
+                    InternetSetCookie(domains[j], cc[i].Name, cc[i].Value);
+                }
+            }
+        }
+        #endregion
+
+        /// <summary>
+        /// 格式化Cookie为标准格式
+        /// </summary>
+        /// <param name="key">Key值</param>
+        /// <param name="value">Value值</param>
+        /// <returns></returns>
+        public static string CookieFormat(string key, string value)
+        {
+            return string.Format("{0}={1};", key, value);
+        }
+    }
+
+    /// <summary>
+    /// Cookie对象
+    /// </summary>
+    public class CookieItem
+    {
+        /// <summary>
+        /// 键
+        /// </summary>
+        public string Key { get; set; }
+        /// <summary>
+        /// 值
+        /// </summary>
+        public string Value { get; set; }
+    }
+}

+ 332 - 0
Masuit.Tools/Net/RedisHelper.cs

@@ -0,0 +1,332 @@
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.IO;
+using System.Net;
+using System.Runtime.Serialization.Formatters.Binary;
+using Newtonsoft.Json;
+using StackExchange.Redis;
+
+namespace Masuit.Tools.Net
+{
+    /// <summary>
+    /// Redis帮助类
+    /// </summary>
+    public static class RedisHelper
+    {
+        private static readonly string Coonstr = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString;
+
+        private static readonly object _locker = new object();
+        private static ConnectionMultiplexer _instance;
+
+        static RedisHelper()
+        {
+        }
+
+        /// <summary>
+        /// 返回已连接的实例, 
+        /// </summary>
+        public static ConnectionMultiplexer Instance
+        {
+            get
+            {
+                if (_instance == null)
+                {
+                    lock (_locker)
+                    {
+                        if ((_instance == null) || !_instance.IsConnected)
+                            _instance = ConnectionMultiplexer.Connect(Coonstr);
+                    }
+                }
+                //注册如下事件
+                _instance.ConnectionFailed += MuxerConnectionFailed;
+                _instance.ConnectionRestored += MuxerConnectionRestored;
+                _instance.ErrorMessage += MuxerErrorMessage;
+                _instance.ConfigurationChanged += MuxerConfigurationChanged;
+                _instance.HashSlotMoved += MuxerHashSlotMoved;
+                _instance.InternalError += MuxerInternalError;
+                return _instance;
+            }
+        }
+
+        /// <summary>
+        /// 获取一个连接实例
+        /// </summary>
+        /// <returns></returns>
+        public static IDatabase GetDatabase()
+        {
+            return Instance.GetDatabase();
+        }
+
+        /// <summary>
+        /// 过期时间
+        /// </summary>
+        /// <param name="Min">分钟</param>
+        /// <returns></returns>
+        private static TimeSpan ExpireTimeSpan(double Min)
+        {
+            bool bl = bool.Parse(ConfigurationManager.AppSettings["UseRedis"]);
+
+            if (bl)
+                return TimeSpan.FromMinutes(Min);
+            return TimeSpan.FromMilliseconds(1);
+        }
+
+        /// <summary>
+        /// 清除 包含特定字符的所有缓存
+        /// </summary>
+        /// <param name="keyStr">键</param>
+        public static void RemoveSpeStr(string keyStr)
+        {
+            List<string> listKeys = GetAllKeys();
+            foreach (string k in listKeys)
+            {
+                if (k.Contains(keyStr))
+                    Remove(k);
+            }
+        }
+
+        /// <summary>
+        /// 判断在缓存中是否存在该key的缓存数据
+        /// </summary>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static bool Exists(string key)
+        {
+            return GetDatabase().KeyExists(key); //可直接调用
+        }
+
+        /// <summary>
+        /// 移除指定key的缓存
+        /// </summary>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static bool Remove(string key)
+        {
+            if (Exists(key))
+                return GetDatabase().KeyDelete(key);
+            return false;
+        }
+
+        /// <summary>
+        ///  Set
+        /// </summary>
+        /// <typeparam name="T">类型</typeparam>
+        /// <param name="key">键</param>
+        /// <param name="t">值</param>
+        /// <param name="minOut">多少分钟后过期,默认值180分钟</param>
+        /// <returns></returns>
+        public static bool Set<T>(string key, T t, double minOut = 60 * 3)
+        {
+            return GetDatabase().StringSet(key, Serialize(t), ExpireTimeSpan(minOut));
+        }
+
+        /// <summary>
+        /// Get
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static T Get<T>(string key)
+        {
+            return Deserialize<T>(GetDatabase().StringGet(key));
+        }
+
+        /// <summary>
+        /// DataSet 缓存
+        /// </summary>
+        /// <param name="key">键</param>
+        /// <param name="ds">内存表集合</param>
+        /// <param name="minOut">过期时间,默认180分钟</param> 
+        public static bool SetData(string key, DataSet ds, double minOut = 60 * 3)
+        {
+            return GetDatabase().StringSet(key, Serialize(ds), ExpireTimeSpan(minOut));
+        }
+
+        /// <summary>
+        /// 获取 DataSet 
+        /// </summary>
+        /// <param name="key">键</param> 
+        public static DataSet GetDataSet(string key)
+        {
+            return Deserialize<DataSet>(GetDatabase().StringGet(key));
+        }
+
+        /// <summary>
+        /// 刷新缓存
+        /// </summary>
+        public static void FlushAll()
+        {
+            var endpoints = Instance.GetEndPoints();
+            var server = Instance.GetServer(endpoints[0]);
+
+            server.FlushDatabase(); // to wipe a single database, 0 by default
+        }
+
+        /// <summary>
+        /// 得到所有缓存键值
+        /// </summary>
+        /// <returns></returns>
+        public static List<string> GetAllKeys()
+        {
+            List<string> lstKey = new List<string>();
+            var endpoints = Instance.GetEndPoints();
+            var server = Instance.GetServer(endpoints[0]);
+            var keys = server.Keys();
+            foreach (var key in keys)
+                lstKey.Add(key);
+            return lstKey;
+        }
+
+        //----------------------------------------------------------------------------------------------------------
+        private static string JsonSerialize(object o)
+        {
+            if (o == null)
+                return null;
+            return JsonConvert.SerializeObject(o);
+        }
+
+        private static T JsonDeserialize<T>(string json)
+        {
+            if (json == null)
+                return default(T);
+            return JsonConvert.DeserializeObject<T>(json);
+        }
+
+        /// <summary>
+        /// 序列化对象
+        /// </summary>
+        /// <param name="o"></param>
+        /// <returns></returns>
+        private static byte[] Serialize(object o)
+        {
+            if (o == null)
+                return null;
+            BinaryFormatter binaryFormatter = new BinaryFormatter();
+            using (MemoryStream memoryStream = new MemoryStream())
+            {
+                binaryFormatter.Serialize(memoryStream, o);
+                byte[] objectDataAsStream = memoryStream.ToArray();
+                return objectDataAsStream;
+            }
+        }
+
+        /// <summary>
+        /// 反序列化对象
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <param name="stream"></param>
+        /// <returns></returns>
+        private static T Deserialize<T>(byte[] stream)
+        {
+            if (stream == null)
+                return default(T);
+            BinaryFormatter binaryFormatter = new BinaryFormatter();
+            using (MemoryStream memoryStream = new MemoryStream(stream))
+            {
+                T result = (T)binaryFormatter.Deserialize(memoryStream);
+                return result;
+            }
+        }
+
+        /// <summary>
+        /// 配置更改时
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        /// <exception cref="Exception"></exception>
+        private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
+        {
+            //LogHelper.LogExceRun("Configuration changed: " + e.EndPoint, new Exception());
+            throw new Exception("配置更改时: " + e.EndPoint);
+        }
+
+        /// <summary>
+        /// 发生错误时
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        /// <exception cref="Exception"></exception>
+        private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
+        {
+            //LogHelper.LogExceRun("ErrorMessage: " + e.Message, new Exception());
+            throw new Exception("发生错误时:" + e.Message);
+        }
+
+        /// <summary>
+        /// 重新建立连接之前的错误
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        /// <exception cref="Exception"></exception>
+        private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
+        {
+            //LogHelper.LogExceRun("ConnectionRestored: " + e.EndPoint, new Exception());
+            throw new Exception("重新建立连接之前的错误: " + e.EndPoint);
+        }
+
+        /// <summary>
+        /// 连接失败 , 如果重新连接成功你将不会收到这个通知
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        /// <exception cref="Exception"></exception>
+        private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
+        {
+            //LogHelper.LogExceRun("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)), new Exception());
+            throw new Exception("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : ", " + e.Exception.Message));
+        }
+
+        /// <summary>
+        /// 更改集群
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        /// <exception cref="Exception"></exception>
+        private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
+        {
+            //LogHelper.LogExceRun("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint, new Exception());
+            throw new Exception("更改集群HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
+        }
+
+        /// <summary>
+        /// redis类库错误
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        /// <exception cref="Exception"></exception>
+        private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
+        {
+            //LogHelper.LogExceRun("redis类库错误InternalError:Message" + e.Exception.Message, new Exception());
+            throw new Exception("redis类库错误InternalError:Message" + e.Exception.Message);
+        }
+
+        /// <summary>
+        /// GetServer方法会接收一个EndPoint类或者一个唯一标识一台服务器的键值对
+        /// 有时候需要为单个服务器指定特定的命令
+        /// 使用IServer可以使用所有的shell命令,比如:
+        /// DateTime lastSave = server.LastSave();
+        /// ClientInfo[] clients = server.ClientList();
+        /// 如果报错在连接字符串后加 ,allowAdmin=true;
+        /// </summary>
+        /// <param name="host">主机地址</param>
+        /// <param name="port">端口号</param>
+        /// <returns></returns>
+        public static IServer GetServer(string host, int port)
+        {
+            IServer server = Instance.GetServer(host, port);
+            return server;
+        }
+
+        /// <summary>
+        /// 获取全部终结点
+        /// </summary>
+        /// <returns></returns>
+        public static EndPoint[] GetEndPoints()
+        {
+            EndPoint[] endpoints = Instance.GetEndPoints();
+            return endpoints;
+        }
+    }
+}

+ 561 - 0
Masuit.Tools/Net/SocketClient.cs

@@ -0,0 +1,561 @@
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Runtime.Serialization;
+using System.Runtime.Serialization.Formatters.Binary;
+using System.Text;
+using System.Threading;
+
+namespace Masuit.Tools.Net
+{
+    /// <summary>
+    /// Socket客户端操作类
+    /// </summary>
+    public static class SocketClient
+    {
+        #region 私有字段
+
+        /// <summary>
+        /// 设置数据缓冲区大小 默认1024
+        /// </summary>
+        private static readonly int m_maxpacket = 1024 * 4;
+
+        #endregion
+
+        #region 服务器侦听
+
+        /// <summary>
+        /// 服务器侦听方法 返回null则说明没有链接上
+        /// </summary>
+        /// <returns>返回一个套接字(Socket)</returns>
+        public static Socket ListenerSocket(this TcpListener listener)
+        {
+            try
+            {
+                Socket socket = listener.AcceptSocket();
+                return socket;
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// 服务器侦听方法 返回null则说明没有链接上
+        /// </summary>
+        /// <param name="listener"></param>
+        /// <returns>返回一个网络流</returns>
+        public static NetworkStream ListenerStream(this TcpListener listener)
+        {
+            try
+            {
+                TcpClient client = listener.AcceptTcpClient();
+                return client.GetStream();
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        #endregion
+
+        #region 客户端连接
+
+        /// <summary>
+        /// 从客户端连接获取socket对象
+        /// </summary>
+        /// <param name="tcpclient">TCP客户端</param>
+        /// <param name="ipendpoint">客户端节点</param>
+        /// <returns></returns>
+        public static Socket ConnectSocket(this TcpClient tcpclient, IPEndPoint ipendpoint)
+        {
+            try
+            {
+                tcpclient.Connect(ipendpoint);
+                return tcpclient.Client;
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// 从客户端连接获取socket对象
+        /// </summary>
+        /// <param name="tcpclient">TCP客户端</param>
+        /// <param name="ipadd">IP地址</param>
+        /// <param name="port">端口号</param>
+        /// <returns></returns>
+        public static Socket ConnectSocket(this TcpClient tcpclient, IPAddress ipadd, int port)
+        {
+            try
+            {
+                tcpclient.Connect(ipadd, port);
+                return tcpclient.Client;
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// 从客户端获取网络流对象
+        /// </summary>
+        /// <param name="tcpclient">TCP客户端</param>
+        /// <param name="ipendpoint">客户端节点</param>
+        /// <returns></returns>
+        public static NetworkStream ConnectStream(this TcpClient tcpclient, IPEndPoint ipendpoint)
+        {
+            try
+            {
+                tcpclient.Connect(ipendpoint);
+                return tcpclient.GetStream();
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// 从客户端获取网络流对象
+        /// </summary>
+        /// <param name="tcpclient">TCP客户端</param>
+        /// <param name="ipadd">IP地址</param>
+        /// <param name="port">端口号</param>
+        /// <returns></returns>
+        public static NetworkStream ConnectStream(this TcpClient tcpclient, IPAddress ipadd, int port)
+        {
+            try
+            {
+                tcpclient.Connect(ipadd, port);
+                return tcpclient.GetStream();
+            }
+            catch
+            {
+                return null;
+            }
+        }
+
+        #endregion
+
+        #region Socket接收数据
+
+        /// <summary>
+        /// 接受固定长度字符串
+        /// </summary>
+        /// <param name="socket">socket对象</param>
+        /// <param name="size">字符串长度</param>
+        /// <returns></returns>
+        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);
+                if (recv == 0)
+                    break;
+                offset += recv;
+                dataleft -= recv;
+            }
+            return msg;
+        }
+
+        /// <summary>
+        /// 接收变长字符串
+        /// 为了处理粘包问题 ,每次发送数据时 包头(数据字节长度) + 正文
+        /// 这个发送小数据
+        /// 设置包头的字节为8,不能超过8位数的字节数组
+        /// </summary>
+        /// <param name="socket"></param>
+        /// <returns>byte[]数组</returns>
+        public static byte[] ReceiveVarData(this Socket socket)
+        {
+            //每次接受数据时,接收固定长度的包头,包头长度为8
+            byte[] lengthbyte = ReceiveFixData(socket, 8);
+            //length得到字符长度 然后加工处理得到数字
+            int length = GetPacketLength(lengthbyte);
+            //得到正文
+            return ReceiveFixData(socket, length);
+        }
+
+        /// <summary>
+        /// 接收T类对象,反序列化
+        /// </summary>
+        /// <typeparam name="T">接收T类对象,T类必须是一个可序列化类</typeparam>
+        /// <param name="socket"></param>
+        /// <returns></returns>
+        public static T ReceiveVarData<T>(this Socket socket)
+        {
+            //先接收包头长度 固定8个字节
+            byte[] lengthbyte = ReceiveFixData(socket, 8);
+            //得到字节长度
+            int length = GetPacketLength(lengthbyte);
+            byte[] bytecoll = new byte[m_maxpacket];
+            IFormatter format = new BinaryFormatter();
+            MemoryStream stream = new MemoryStream();
+            int offset = 0; //接收字节个数
+            int lastdata = length; //还剩下多少没有接收,初始大小等于实际大小
+            int receivedata = m_maxpacket; //每次接收大小
+            //循环接收
+            int mark = 0; //标记几次接收到的数据为0长度
+            while (true)
+            {
+                //剩下的字节数是否小于缓存大小
+                if (lastdata < m_maxpacket)
+                    receivedata = lastdata; //就只接收剩下的字节数
+                int count = socket.Receive(bytecoll, 0, receivedata, 0);
+                if (count > 0)
+                {
+                    stream.Write(bytecoll, 0, count);
+                    offset += count;
+                    lastdata -= count;
+                    mark = 0;
+                }
+                else
+                {
+                    mark++;
+                    if (mark == 10)
+                        break;
+                }
+                if (offset == length)
+                    break;
+            }
+            stream.Seek(0, SeekOrigin.Begin); //必须要这个 或者stream.Position = 0;
+            T t = (T)format.Deserialize(stream);
+            stream.Close();
+            return t;
+        }
+
+        /// <summary>
+        /// 在预先得到文件的文件名和大小
+        /// 调用此方法接收文件
+        /// </summary>
+        /// <param name="socket">socket服务端</param>
+        /// <param name="path">路径必须存在</param>
+        /// <param name="filename">文件名</param>
+        /// <param name="size">预先知道的文件大小</param>
+        /// <param name="progress">处理过程</param>
+        public static bool ReceiveFile(this Socket socket, string path, string filename, long size, Action<int> progress)
+        {
+            bool ret = false;
+            if (Directory.Exists(path))
+            {
+                //主要是防止有重名文件
+                string savepath = GetPath(path, filename); //得到文件路径
+                //缓冲区
+                byte[] file = new byte[m_maxpacket];
+                int count = 0; //每次接收的实际长度
+                int receivedata = m_maxpacket; //每次要接收的长度
+                long offset = 0; //循环接收的总长度
+                long lastdata = size; //剩余多少还没接收
+                int mark = 0;
+                using (FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write))
+                {
+                    if (size > 0)
+                        while (true)
+                        {
+                            if (lastdata < receivedata)
+                                receivedata = Convert.ToInt32(lastdata);
+                            count = socket.Receive(file, 0, receivedata, SocketFlags.None);
+                            if (count > 0)
+                            {
+                                fs.Write(file, 0, count);
+                                offset += count;
+                                lastdata -= count;
+                                mark = 0;
+                            }
+                            else
+                            {
+                                mark++; //连续5次接收为0字节 则跳出循环
+                                if (mark == 10)
+                                    break;
+                            }
+                            //接收进度
+                            if (progress != null)
+                                progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
+                            //接收完毕
+                            if (offset == size)
+                            {
+                                ret = true;
+                                break;
+                            }
+                        }
+                    fs.Close();
+                }
+            }
+            return ret;
+        }
+
+        /// <summary>
+        /// 从socket服务端接收文件
+        /// </summary>
+        /// <param name="socket">socket服务端</param>
+        /// <param name="path">文件保存路径(必须存在)</param>
+        /// <param name="filename">文件名</param>
+        /// <param name="size">预先知道的文件大小</param>
+        /// <returns></returns>
+        public static bool ReceiveFile(this Socket socket, string path, string filename, long size)
+        {
+            return ReceiveFile(socket, path, filename, size, null);
+        }
+
+        /// <summary>
+        /// 预先不知道文件名和文件大小 用此方法接收
+        /// 此方法对于的发送方法是SendFile()
+        /// </summary>
+        /// <param name="socket">socket服务端</param>
+        /// <param name="path">要保存的目录</param>
+        public static void ReceiveFile(this Socket socket, string path)
+        {
+            //得到包头信息字节数组 (文件名 + 文件大小 的字符串长度)
+            //取前8位
+            byte[] info_bt = ReceiveFixData(socket, 8);
+            //得到包头信息字符长度
+            int info_length = GetPacketLength(info_bt);
+            //提取包头信息,(文件名 + 文件大小 的字符串长度)
+            byte[] info = ReceiveFixData(socket, info_length);
+            //得到文件信息字符串 (文件名 + 文件大小)
+            string info_str = Encoding.UTF8.GetString(info);
+            string[] strs = info_str.Split('|');
+            string filename = strs[0]; //文件名
+            long length = Convert.ToInt64(strs[1]); //文件大小
+            //开始接收文件
+            ReceiveFile(socket, path, filename, length);
+        }
+
+        private static int GetPacketLength(byte[] length)
+        {
+            string str = Encoding.UTF8.GetString(length);
+            str = str.TrimEnd('*');
+            ; //("*", "");
+            int _length = 0;
+            if (int.TryParse(str, out _length))
+                return _length;
+            return 0;
+        }
+
+        private static int i;
+
+        private static string markPath = string.Empty;
+        /// <summary>
+        /// 得到文件路径(防止有文件名重复)
+        ///  如:aaa.txt已经在directory目录下存在,则会得到文件aaa(1).txt
+        /// </summary>
+        /// <param name="directory">目录名</param>
+        /// <param name="file">文件名</param>
+        /// <returns>文件路径</returns>
+
+        public static string GetPath(string directory, string file)
+        {
+            if (markPath == string.Empty)
+                markPath = Path.Combine(directory, file);
+            string path = Path.Combine(directory, file);
+            if (File.Exists(path))
+            {
+                i++;
+                string filename = Path.GetFileNameWithoutExtension(markPath) + "(" + i + ")";
+                string extension = Path.GetExtension(markPath);
+                return GetPath(directory, filename + extension);
+            }
+            i = 0;
+            markPath = string.Empty;
+            return path;
+        }
+
+        #endregion
+
+        #region Socket发送数据
+
+        /// <summary>
+        /// 发送固定长度消息
+        /// 发送字节数不能大于int型最大值
+        /// </summary>
+        /// <param name="socket"></param>
+        /// <param name="msg"></param>
+        /// <returns>返回发送字节个数</returns>
+        public static int SendFixData(this Socket socket, byte[] msg)
+        {
+            int size = msg.Length; //要发送字节长度
+            int offset = 0; //已经发送长度
+            int dataleft = size; //剩下字符
+            int senddata = m_maxpacket; //每次发送大小
+            while (true)
+            {
+                //如过剩下的字节数 小于 每次发送字节数
+                if (dataleft < senddata)
+                    senddata = dataleft;
+                int count = socket.Send(msg, offset, senddata, SocketFlags.None);
+                offset += count;
+                dataleft -= count;
+                if (offset == size)
+                    break;
+            }
+            return offset;
+        }
+
+        /// <summary>
+        /// 发送变长信息 格式 包头(包头占8位) + 正文
+        /// </summary>
+        /// <param name="socket"></param>
+        /// <param name="contact">发送文本</param>
+        /// <returns></returns>
+        public static int SendVarData(this Socket socket, string contact)
+        {
+            //得到字符长度
+            int size = Encoding.UTF8.GetBytes(contact).Length;
+            //包头字符
+            string length = GetSendPacketLengthStr(size);
+            //包头 + 正文
+            byte[] sendbyte = Encoding.UTF8.GetBytes(length + contact);
+            //发送
+            return SendFixData(socket, sendbyte);
+        }
+
+        /// <summary>
+        /// 发送变成信息
+        /// </summary>
+        /// <param name="socket"></param>
+        /// <param name="bytes"></param>
+        /// <returns></returns>
+        public static int SendVarData(this Socket socket, byte[] bytes)
+        {
+            //得到包头字节
+            int size = bytes.Length;
+            string length = GetSendPacketLengthStr(size);
+            byte[] lengthbyte = Encoding.UTF8.GetBytes(length);
+            //发送包头
+            SendFixData(socket, lengthbyte); //因为不知道正文是什么编码所以没有合并
+            //发送正文
+            return SendFixData(socket, bytes);
+        }
+
+        /// <summary>
+        /// 发送T类型对象,序列化
+        /// </summary>
+        /// <typeparam name="T">T类型</typeparam>
+        /// <param name="socket"></param>
+        /// <param name="obj">T类型对象,必须是可序列化的</param>
+        /// <returns></returns>
+        public static int SendSerializeObject<T>(this Socket socket, T obj)
+        {
+            byte[] bytes = SerializeObject(obj);
+            return SendVarData(socket, bytes);
+        }
+
+        /// <summary>
+        /// 发送文件
+        /// </summary>
+        /// <param name="socket">socket对象</param>
+        /// <param name="path">文件路径</param>
+        /// <param name="issend">是否发送文件(头)信息,如果当前知道文件[大小,名称]则为false</param>
+        /// <param name="progress"></param>
+        /// <returns></returns>
+        public static bool SendFile(this Socket socket, string path, bool issend, Action<int> progress)
+        {
+            bool ret = false;
+            if (File.Exists(path))
+            {
+                FileInfo fileinfo = new FileInfo(path);
+                string filename = fileinfo.Name;
+                long length = fileinfo.Length;
+                //发送文件信息
+                if (issend)
+                    SendVarData(socket, filename + "|" + length);
+                //发送文件
+                long offset = 0;
+                byte[] b = new byte[m_maxpacket];
+                int mark = 0;
+                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
+                {
+                    int senddata = b.Length;
+                    long i = length;
+                    //循环读取发送
+                    while (true)
+                    {
+                        int count = fs.Read(b, 0, senddata);
+                        if (count > 0)
+                        {
+                            socket.Send(b, 0, count, SocketFlags.None);
+                            offset += count;
+                            mark = 0;
+                        }
+                        else
+                        {
+                            mark++;
+                            if (mark == 10)
+                                break;
+                        }
+                        if (progress != null)
+                            progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
+                        if (offset == length)
+                            break;
+                        Thread.Sleep(50); //设置等待时间,以免粘包
+                    }
+                }
+            }
+            return ret;
+        }
+
+        /// <summary>
+        /// 发送文件,不需要进度信息
+        /// </summary>
+        /// <param name="socket">socket对象</param>
+        /// <param name="path">文件路径</param>
+        /// <param name="issend">是否发生(头)信息</param>
+        /// <returns></returns>
+        public static bool SendFile(this Socket socket, string path, bool issend)
+        {
+            return SendFile(socket, path, issend, null);
+        }
+
+        /// <summary>
+        /// 发送文件,不需要进度信息和(头)信息
+        /// </summary>
+        /// <param name="socket">socket对象</param>
+        /// <param name="path">文件路径</param>
+        /// <returns></returns>
+        public static bool SendFile(this Socket socket, string path)
+        {
+            return SendFile(socket, path, false, null);
+        }
+
+        private static byte[] SerializeObject(object obj)
+        {
+            IFormatter format = new BinaryFormatter();
+            MemoryStream stream = new MemoryStream();
+            format.Serialize(stream, obj);
+            byte[] ret = stream.ToArray();
+            stream.Close();
+            return ret;
+        }
+
+        private static string GetSendPacketLengthStr(int size)
+        {
+            string length = size + "********"; //得到size的长度
+            return length.Substring(0, 8); //截取前前8位
+        }
+
+        #endregion
+
+        #region NetworkStream接收数据
+
+        //没写
+
+        #endregion
+
+        #region NetworkStream发送数据
+
+        //没写
+
+        #endregion
+    }
+}

+ 165 - 0
Masuit.Tools/Net/WebExtension.cs

@@ -0,0 +1,165 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Mail;
+using System.Runtime.Remoting.Messaging;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using System.Web;
+using System.Web.Script.Serialization;
+using Masuit.Utilities.Models;
+
+namespace Masuit.Tools.Net
+{
+    /// <summary>
+    /// Web操作扩展
+    /// </summary>
+    public static class WebExtension
+    {
+        #region 获取线程内唯一的EF上下文对象
+
+        /// <summary>
+        /// 获取线程内唯一的EF上下文对象
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <returns></returns>
+        public static T GetDbContext<T>() where T : new()
+        {
+            T db;
+            if (CallContext.GetData("db") == null) //由于CallContext比HttpContext先存在,所以首选CallContext为线程内唯一对象
+            {
+                db = new T();
+                CallContext.SetData("db", db);
+            }
+            db = (T)CallContext.GetData("db");
+            return db;
+        }
+
+        #endregion
+
+        #region 发送邮件
+
+        /// <summary>
+        /// 发送邮件
+        /// </summary>
+        /// <param name="mail">邮箱对象</param>
+        /// <returns>发送成功</returns>
+        public static bool Sendmail(this Email mail)
+        {
+            using (MailMessage msg = new MailMessage())
+            {
+                msg.To.Add(mail.To);
+                msg.From = new MailAddress(mail.MailAccount, mail.Subject);
+                msg.Subject = mail.Subject; //邮件标题
+                msg.SubjectEncoding = Encoding.UTF8; //邮件标题编码
+                msg.Body = mail.Body; //邮件内容
+                msg.BodyEncoding = Encoding.UTF8; //邮件内容编码
+                msg.IsBodyHtml = mail.IsHtml; //是否是HTML邮件
+                msg.Priority = MailPriority.High; //邮件优先级
+                SmtpClient client = new SmtpClient();
+                client.Credentials = new NetworkCredential(mail.MailAccount, mail.Password);
+                client.Host = mail.Smtp;
+                object userState = msg;
+                try
+                {
+                    client.Send(msg);
+                    return true;
+                }
+                catch
+                {
+                    return false;
+                }
+            }
+        }
+        /// <summary>
+        /// 发送邮件
+        /// </summary>
+        /// <param name="mail">邮箱对象</param>
+        /// <returns>发送成功</returns>
+        public static bool SendmailAsync(this Email mail)
+        {
+            using (MailMessage msg = new MailMessage())
+            {
+                msg.To.Add(mail.To);
+                msg.From = new MailAddress(mail.MailAccount, mail.Subject);
+                msg.Subject = mail.Subject; //邮件标题
+                msg.SubjectEncoding = Encoding.UTF8; //邮件标题编码
+                msg.Body = mail.Body; //邮件内容
+                msg.BodyEncoding = Encoding.UTF8; //邮件内容编码
+                msg.IsBodyHtml = mail.IsHtml; //是否是HTML邮件
+                msg.Priority = MailPriority.High; //邮件优先级
+                SmtpClient client = new SmtpClient();
+                client.Credentials = new NetworkCredential(mail.MailAccount, mail.Password);
+                client.Host = mail.Smtp;
+                object userState = msg;
+                try
+                {
+                    client.SendAsync(msg, userState);
+                    return true;
+                }
+                catch
+                {
+                    return false;
+                }
+            }
+        }
+
+        #endregion
+
+        #region 写Session
+
+        /// <summary>
+        /// 写Session
+        /// </summary>
+        /// <param name="key">键</param>
+        /// <param name="value">值</param>
+        public static void SetSession(string key, dynamic value) => HttpContext.Current.Session[key] = value;
+
+        #endregion
+
+        #region 获取Session
+
+        /// <summary>
+        /// 获取Session
+        /// </summary>
+        /// <typeparam name="T">对象</typeparam>
+        /// <param name="key">键</param>
+        /// <returns>对象</returns>
+        public static T GetSession<T>(string key) => (T)HttpContext.Current.Session[key];
+
+        #endregion
+
+        #region 获取客户端IP地址信息
+
+        /// <summary>
+        /// 获取客户端IP地址信息
+        /// </summary>
+        /// <param name="ip">IP地址</param>
+        /// <returns></returns>
+        public static async Task<IPData> GetIPAddressInfoAsync(this string ip)
+        {
+            HttpClient client = new HttpClient();
+            JavaScriptSerializer serializer = new JavaScriptSerializer();
+            INetAddress ipAddress; //IP地址对象变量声明
+            Match match = Regex.Match(ip, @"\d+\.\d+\.\d+\.\d+"); //IP地址正则
+            if (match.Success)
+            {
+                try
+                {
+                    string ipData = await client.GetStringAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}").ConfigureAwait(false); //根据API地址获取
+                    ipAddress = serializer.Deserialize<INetAddress>(ipData); //将获取到的json数据反序列化为对象
+                    return ipAddress.data;
+                }
+                catch (Exception)
+                {
+                    return new INetAddress { data = { region = "未能获取到IP地址信息" } }.data; //如果发生异常,则构造一个空对象
+                }
+            }
+
+            return new INetAddress { data = { region = "IP地址格式不正确" } }.data; //如果发生异常,则构造一个空对象
+        }
+
+        #endregion
+    }
+}

+ 39 - 0
Masuit.Tools/Properties/AssemblyInfo.cs

@@ -0,0 +1,39 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+
+[assembly: AssemblyTitle("Masuit.Utilities")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Masuit.Utilities")]
+[assembly: AssemblyCopyright("Copyright ©  2017")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+//将 ComVisible 设置为 false 将使此程序集中的类型
+//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+//请将此类型的 ComVisible 特性设置为 true。
+
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+
+[assembly: Guid("275d5a0d-c49c-497e-a4b5-f40285c2495f")]
+
+// 程序集的版本信息由下列四个值组成: 
+//
+//      主版本
+//      次版本
+//      生成号
+//      修订号
+//
+//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: :
+// [assembly: AssemblyVersion("1.0.*")]
+
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 220 - 0
Masuit.Tools/Reflection/ReflectHelper.cs

@@ -0,0 +1,220 @@
+using System;
+using System.ComponentModel;
+using System.Drawing;
+using System.IO;
+using System.Reflection;
+using System.Resources;
+using System.Text;
+
+namespace Masuit.Tools.Reflection
+{
+    /// <summary>
+    /// 反射辅助类
+    /// </summary>
+    public static class ReflectHelper
+    {
+        #region 成员读写
+        /// <summary>
+        /// 获取实体相关属性的值
+        /// </summary>
+        /// <param name="obj"></param>
+        /// <param name="propertyName"></param>
+        /// <returns></returns>
+        public static object GetInstanceValue(this object obj, string propertyName)
+        {
+            object objRet = null;
+            if (!string.IsNullOrEmpty(propertyName))
+            {
+                PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj).Find(propertyName, true);
+                if (descriptor != null)
+                {
+                    objRet = descriptor.GetValue(obj);
+                }
+            }
+            return objRet;
+        }
+        #endregion
+
+        #region 方法调用
+        /// <summary>
+        /// 直接调用内部对象的方法/函数或获取属性(支持重载调用)
+        /// </summary>
+        /// <typeparam name="T">泛型T</typeparam>
+        /// <param name="refType">目标数据类型</param>
+        /// <param name="funName">函数名称,区分大小写。</param>
+        /// <param name="objInitial">如果调用属性,则为相关对象的初始化数据,否则为Null。</param>
+        /// <param name="funParams">函数参数信息</param>
+        /// <returns>运行结果</returns>
+        /// <exception cref="InvalidProgramException"></exception>
+        public static T InvokeMethodOrGetProperty<T>(this Type refType, string funName, object[] objInitial, params object[] funParams)
+        {
+            MemberInfo[] mis = refType.GetMember(funName);
+            if (mis.Length < 1)
+            {
+                throw new InvalidProgramException(string.Concat("函数/方法 [", funName, "] 在指定类型(", refType.ToString(), ")中不存在!"));
+            }
+            else
+            {
+                MethodInfo targetMethod = null;
+                StringBuilder pb = new StringBuilder();
+                foreach (MemberInfo mi in mis)
+                {
+                    if (mi.MemberType != MemberTypes.Method)
+                    {
+                        if (mi.MemberType == MemberTypes.Property)
+                        {
+                            #region 调用属性方法Get
+                            targetMethod = ((PropertyInfo)mi).GetGetMethod();
+                            break;
+                            #endregion
+                        }
+                        else
+                        {
+                            throw new InvalidProgramException(string.Concat("[", funName, "] 不是有效的函数/属性方法!"));
+                        }
+                    }
+                    else
+                    {
+                        #region 检查函数参数和数据类型 绑定正确的函数到目标调用
+                        bool validParamsLen = false, validParamsType = false;
+
+                        MethodInfo curMethod = (MethodInfo)mi;
+                        ParameterInfo[] pis = curMethod.GetParameters();
+                        if (pis.Length == funParams.Length)
+                        {
+                            validParamsLen = true;
+
+                            pb = new StringBuilder();
+                            bool paramFlag = true;
+                            int paramIdx = 0;
+
+                            #region 检查数据类型 设置validParamsType是否有效
+                            foreach (ParameterInfo pi in pis)
+                            {
+                                pb.AppendFormat("Parameter {0}: Type={1}, Name={2}\n", paramIdx, pi.ParameterType, pi.Name);
+
+                                //不对Null和接受Object类型的参数检查
+                                if (funParams[paramIdx] != null && pi.ParameterType != typeof(object) && (pi.ParameterType != funParams[paramIdx].GetType()))
+                                {
+                                    #region 检查类型是否兼容
+                                    try
+                                    {
+                                        funParams[paramIdx] = Convert.ChangeType(funParams[paramIdx], pi.ParameterType);
+                                    }
+                                    catch (Exception)
+                                    {
+                                        paramFlag = false;
+                                    }
+                                    #endregion
+                                    //break;
+                                }
+                                ++paramIdx;
+                            }
+                            #endregion
+
+                            if (paramFlag)
+                            {
+                                validParamsType = true;
+                            }
+                            else
+                            {
+                                continue;
+                            }
+
+                            if (validParamsLen && validParamsType)
+                            {
+                                targetMethod = curMethod;
+                                break;
+                            }
+                        }
+                        #endregion
+                    }
+                }
+
+                if (targetMethod != null)
+                {
+                    object objReturn = null;
+                    #region 兼顾效率和兼容重载函数调用
+                    try
+                    {
+                        object objInstance = System.Activator.CreateInstance(refType, objInitial);
+                        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;
+                }
+                else
+                {
+                    throw new InvalidProgramException(string.Concat("函数/方法 [", refType.ToString(), ".", funName, "(args ...) ] 参数长度和数据类型不正确!\n 引用参数信息参考:\n", pb.ToString()));
+                }
+            }
+        }
+
+        /// <summary>
+        /// 调用相关实体类型的函数方法
+        /// </summary>
+        /// <typeparam name="T">泛型T</typeparam>
+        /// <param name="refType">实体类型</param>
+        /// <param name="funName">函数名称</param>
+        /// <param name="funParams">函数参数列表</param>
+        /// <returns>调用该函数之后的结果</returns>
+        public static T InvokeFunction<T>(Type refType, string funName, params object[] funParams)
+        {
+            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(Type assemblyType, string resourceHolder, string imageName)
+        {
+            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
+            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
+            return (Bitmap)rm.GetObject(imageName);
+        }
+
+        /// <summary>
+        ///  获取程序集资源的文本资源
+        /// </summary>
+        /// <param name="assemblyType">程序集中的某一对象类型</param>
+        /// <param name="resName">资源项名称</param>
+        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
+        public static string GetStringRes(Type assemblyType, string resName, string resourceHolder)
+        {
+            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
+            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
+            return rm.GetString(resName);
+        }
+
+        /// <summary>
+        /// 获取程序集嵌入资源的文本形式
+        /// </summary>
+        /// <param name="assemblyType">程序集中的某一对象类型</param>
+        /// <param name="charset">字符集编码</param>
+        /// <param name="ResName">嵌入资源相对路径</param>
+        /// <returns>如没找到该资源则返回空字符</returns>
+        public static string GetManifestString(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;
+            byte[] bytes = new byte[iLen];
+            st.Read(bytes, 0, iLen);
+            return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
+        }
+        #endregion
+
+    }
+}

+ 418 - 0
Masuit.Tools/Reflection/ReflectionUtil.cs

@@ -0,0 +1,418 @@
+using System;
+using System.ComponentModel;
+using System.Drawing;
+using System.IO;
+using System.Reflection;
+using System.Resources;
+using System.Text;
+
+namespace Masuit.Tools.Reflection
+{
+    /// <summary>
+    /// 反射操作辅助类,如获取或设置字段、属性的值等反射信息。
+    /// </summary>
+    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
+
+        /// <summary>
+        /// 执行方法
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <param name="methodName">方法名,区分大小写</param>
+        /// <param name="args">方法参数</param>
+        /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
+        /// <returns>T类型</returns>
+        public static T InvokeMethod<T>(this object obj, string methodName, object[] args) where T : class
+        {
+            T objReturn;
+            Type type = obj.GetType();
+            objReturn = type.InvokeMember(methodName, bf | BindingFlags.InvokeMethod, null, obj, args) as T;
+            return objReturn;
+        }
+
+        /// <summary>
+        /// 设置字段
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <param name="name">字段名</param>
+        /// <param name="value">值</param>
+        public static void SetField(this object obj, string name, object value)
+        {
+            FieldInfo fi = obj.GetType().GetField(name, bf);
+            fi.SetValue(obj, value);
+        }
+
+        /// <summary>
+        /// 获取字段
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <param name="name">字段名</param>
+        /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
+        /// <returns>T类型</returns>
+        public static T GetField<T>(this object obj, string name) where T : class
+        {
+            FieldInfo fi = obj.GetType().GetField(name, bf);
+            return fi.GetValue(obj) as T;
+        }
+
+        /// <summary>
+        /// 获取所有的字段信息
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <returns>字段信息</returns>
+        public static FieldInfo[] GetFields(this object obj)
+        {
+            FieldInfo[] fieldInfos = obj.GetType().GetFields(bf);
+            return fieldInfos;
+        }
+
+        /// <summary>
+        /// 设置属性
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <param name="name">属性名</param>
+        /// <param name="value">值</param>
+        public static void SetProperty(this object obj, string name, object value)
+        {
+            PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
+            value = Convert.ChangeType(value, fieldInfo.PropertyType);
+            fieldInfo.SetValue(obj, value, null);
+        }
+
+        /// <summary>
+        /// 获取属性
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <param name="name">属性名</param>
+        /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
+        /// <returns>T类型</returns>
+        public static T GetProperty<T>(this object obj, string name) where T : class
+        {
+            PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
+            return fieldInfo.GetValue(obj, null) as T;
+        }
+
+        /// <summary>
+        /// 获取所有的属性信息
+        /// </summary>
+        /// <param name="obj">反射对象</param>
+        /// <returns>属性信息</returns>
+        public static PropertyInfo[] GetProperties(this object obj)
+        {
+            PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bf);
+            return propertyInfos;
+        }
+
+        #endregion
+
+        #region 获取Description
+
+        /// <overloads>
+        ///		Get The Member Description using Description Attribute.
+        /// </overloads>
+        /// <summary>
+        /// Get The Enum Field Description using Description Attribute.
+        /// </summary>
+        /// <param name="value">The value.</param>
+        /// <returns>return description or value.ToString()</returns>
+        public static string GetDescription(Enum value)
+        {
+            return GetDescription(value, null);
+        }
+
+        /// <summary>
+        /// Get The Enum Field Description using Description Attribute and 
+        /// objects to format the Description.
+        /// </summary>
+        /// <param name="value">Enum For Which description is required.</param>
+        /// <param name="args">An Object array containing zero or more objects to format.</param>
+        /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
+        /// <exception cref="ArgumentNullException"><paramref name="value"/>"/> is <c>null</c>.</exception>
+        public static string GetDescription(Enum value, params object[] args)
+        {
+            if (value == null)
+            {
+                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();
+
+            if ((args != null) && (args.Length > 0))
+            {
+                return string.Format(null, text1, args);
+            }
+            return text1;
+        }
+
+        /// <summary>
+        ///	Get The Type Description using Description Attribute.
+        /// </summary>
+        /// <param name="member">Specified Member for which Info is Required</param>
+        /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
+        public static string GetDescription(MemberInfo member)
+        {
+            return GetDescription(member, null);
+        }
+
+        /// <summary>
+        /// Get The Type Description using Description Attribute and 
+        /// objects to format the Description.
+        /// </summary>
+        /// <param name="member"> Specified Member for which Info is Required</param>
+        /// <param name="args">An Object array containing zero or more objects to format.</param>
+        /// <returns>return <see cref="String.Empty"/> if DescriptionAttribute is 
+        /// not found or return type description</returns>
+        /// <exception cref="ArgumentNullException"><paramref name="member"/>"/> is <c>null</c>.</exception>
+        public static string GetDescription(MemberInfo member, params object[] args)
+        {
+            string text1;
+
+            if (member == null)
+            {
+                throw new ArgumentNullException(nameof(member));
+            }
+
+            if (member.IsDefined(typeof(DescriptionAttribute), false))
+            {
+                DescriptionAttribute[] attributes =
+                    (DescriptionAttribute[])member.GetCustomAttributes(typeof(DescriptionAttribute), false);
+                text1 = attributes[0].Description;
+            }
+            else
+            {
+                return System.String.Empty;
+            }
+
+            if ((args != null) && (args.Length > 0))
+            {
+                return System.String.Format(null, text1, args);
+            }
+            return text1;
+        }
+
+        #endregion
+
+        #region 获取Attribute信息
+
+        /// <overloads>
+        /// Gets the specified object attributes
+        /// </overloads>
+        /// <summary>
+        /// Gets the specified object attributes for assembly as specified by type
+        /// </summary>
+        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
+        /// <param name="assembly">the assembly in which the specified attribute is defined</param>
+        /// <returns>Attribute as Object or null if not found.</returns>
+        /// <exception cref="ArgumentNullException"><paramref name="attributeType"/>"/> is <c>null</c>.</exception>
+        public static object GetAttribute(Type attributeType, Assembly assembly)
+        {
+            if (attributeType == null)
+            {
+                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;
+        }
+
+        /// <summary>
+        /// Gets the specified object attributes for type as specified by type
+        /// </summary>
+        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
+        /// <param name="type">the type on which the specified attribute is defined</param>
+        /// <returns>Attribute as Object or null if not found.</returns>
+        public static object GetAttribute(Type attributeType, MemberInfo type)
+        {
+            return GetAttribute(attributeType, type, false);
+        }
+
+        /// <summary>
+        /// Gets the specified object attributes for type as specified by type with option to serach parent
+        /// </summary>
+        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
+        /// <param name="type">the type on which the specified attribute is defined</param>
+        /// <param name="searchParent">if set to <see langword="true"/> [search parent].</param>
+        /// <returns>
+        /// Attribute as Object or null if not found.
+        /// </returns>
+        public static object GetAttribute(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);
+
+                if (attributes.Length > 0)
+                {
+                    return attributes[0];
+                }
+            }
+            return null;
+        }
+
+        /// <summary>
+        /// Gets the collection of all specified object attributes for type as specified by type
+        /// </summary>
+        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
+        /// <param name="type">the type on which the specified attribute is defined</param>
+        /// <returns>Attribute as Object or null if not found.</returns>
+        public static object[] GetAttributes(Type attributeType, MemberInfo type)
+        {
+            return GetAttributes(attributeType, type, false);
+        }
+
+        /// <summary>
+        /// Gets the collection of all specified object attributes for type as specified by type with option to serach parent
+        /// </summary>
+        /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
+        /// <param name="type">the type on which the specified attribute is defined</param>
+        /// <param name="searchParent">The attribute Type for which the custom attribute is to be returned.</param>
+        /// <returns>
+        /// Attribute as Object or null if not found.
+        /// </returns>
+        public static object[] GetAttributes(Type attributeType, MemberInfo type, bool searchParent)
+        {
+            if (type == null)
+            {
+                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;
+        }
+
+        #endregion
+
+        #region 资源获取
+
+        /// <summary>
+        /// 根据资源名称获取图片资源流
+        /// </summary>
+        /// <param name="ResourceName"></param>
+        /// <returns></returns>
+        public static Stream GetImageResource(string ResourceName)
+        {
+            Assembly asm = Assembly.GetExecutingAssembly();
+            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(Type assemblyType, string resourceHolder, string imageName)
+        {
+            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
+            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
+            return (Bitmap)rm.GetObject(imageName);
+        }
+
+        /// <summary>
+        ///  获取程序集资源的文本资源
+        /// </summary>
+        /// <param name="assemblyType">程序集中的某一对象类型</param>
+        /// <param name="resName">资源项名称</param>
+        /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
+        public static string GetStringRes(Type assemblyType, string resName, string resourceHolder)
+        {
+            Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
+            ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
+            return rm.GetString(resName);
+        }
+
+        /// <summary>
+        /// 获取程序集嵌入资源的文本形式
+        /// </summary>
+        /// <param name="assemblyType">程序集中的某一对象类型</param>
+        /// <param name="charset">字符集编码</param>
+        /// <param name="ResName">嵌入资源相对路径</param>
+        /// <returns>如没找到该资源则返回空字符</returns>
+        public static string GetManifestString(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;
+            byte[] bytes = new byte[iLen];
+            st.Read(bytes, 0, iLen);
+            return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
+        }
+
+        #endregion
+
+        #region 创建对应实例
+        /// <summary>
+        /// 创建对应实例
+        /// </summary>
+        /// <param name="type">类型</param>
+        /// <returns>对应实例</returns>
+        public static object CreateInstance(string type)
+        {
+            Type tmp = null;
+            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
+            for (int i = 0; i < assemblies.Length; i++)
+            {
+                tmp = assemblies[i].GetType(type);
+                if (tmp != null)
+                {
+                    return assemblies[i].CreateInstance(type);
+                }
+            }
+            return null;
+            //return Assembly.GetExecutingAssembly().CreateInstance(type);
+        }
+
+        /// <summary>
+        /// 创建对应实例
+        /// </summary>
+        /// <param name="type">类型</param>
+        /// <returns>对应实例</returns>
+        public static object CreateInstance(Type type)
+        {
+            return CreateInstance(type.FullName);
+        }
+        #endregion
+    }
+}

+ 544 - 0
Masuit.Tools/Security/AESEncode.cs

@@ -0,0 +1,544 @@
+using System;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text;
+
+//加密字符串,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) 
+//public string DesEncrypt(string strText, string strEncrKey) 
+
+//解密字符串,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) 
+//public string DesDecrypt(string strText,string sDecrKey) 
+
+//加密数据文件,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) 
+//public void DesEncrypt(string m_InFilePath,string m_OutFilePath,string strEncrKey) 
+
+//解密数据文件,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) 
+//public void DesDecrypt(string m_InFilePath,string m_OutFilePath,string sDecrKey) 
+
+//MD5加密 
+//public string MD5Encrypt(string strText) 
+
+namespace Masuit.Tools.Security
+{
+    /// <summary>
+    /// DES对称加解密、AES RijndaelManaged加解密、Base64加密解密、MD5加密等操作辅助类
+    /// </summary>
+    public static class EncodeHelper
+    {
+        #region DES对称加密解密
+        /// <summary>
+        /// 默认的加密密钥
+        /// </summary>
+        public const string DEFAULT_ENCRYPT_KEY = "12345678";
+
+        /// <summary>
+        /// 使用默认加密
+        /// </summary>
+        /// <param name="strText"></param>
+        /// <returns></returns>
+        public static string DesEncrypt(string strText)
+        {
+            try
+            {
+                return DesEncrypt(strText, DEFAULT_ENCRYPT_KEY);
+            }
+            catch
+            {
+                return "";
+            }
+        }
+
+        /// <summary>
+        /// 使用默认解密
+        /// </summary>
+        /// <param name="strText"></param>
+        /// <returns></returns>
+        public static string DesDecrypt(string strText)
+        {
+            try
+            {
+                return DesDecrypt(strText, DEFAULT_ENCRYPT_KEY);
+            }
+            catch
+            {
+                return "";
+            }
+        }
+
+        /// <summary> 
+        /// Encrypt the string 
+        /// Attention:key must be 8 bits 
+        /// </summary> 
+        /// <param name="strText">string</param> 
+        /// <param name="strEncrKey">key</param> 
+        /// <returns></returns> 
+        public static string DesEncrypt(string strText, string strEncrKey)
+        {
+            byte[] byKey = null;
+            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
+
+            byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
+            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
+            byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
+            MemoryStream ms = new MemoryStream();
+            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
+            cs.Write(inputByteArray, 0, inputByteArray.Length);
+            cs.FlushFinalBlock();
+            return Convert.ToBase64String(ms.ToArray());
+        }
+
+        /// <summary> 
+        /// Decrypt string 
+        /// Attention:key must be 8 bits 
+        /// </summary> 
+        /// <param name="strText">Decrypt string</param> 
+        /// <param name="sDecrKey">key</param> 
+        /// <returns>output string</returns> 
+        public static string DesDecrypt(string strText, string sDecrKey)
+        {
+            byte[] byKey = null;
+            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
+            byte[] inputByteArray = new Byte[strText.Length];
+
+            byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
+            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
+            inputByteArray = Convert.FromBase64String(strText);
+            MemoryStream ms = new MemoryStream();
+            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
+            cs.Write(inputByteArray, 0, inputByteArray.Length);
+            cs.FlushFinalBlock();
+            Encoding encoding = new UTF8Encoding();
+            return encoding.GetString(ms.ToArray());
+        }
+
+        /// <summary> 
+        /// Encrypt files 
+        /// Attention:key must be 8 bits 
+        /// </summary> 
+        /// <param name="m_InFilePath">Encrypt file path</param> 
+        /// <param name="m_OutFilePath">output file</param> 
+        /// <param name="strEncrKey">key</param> 
+        public static void DesEncrypt(string m_InFilePath, string m_OutFilePath, string strEncrKey)
+        {
+            byte[] byKey = null;
+            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
+
+            byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
+            FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
+            FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
+            fout.SetLength(0);
+            //Create variables to help with read and write. 
+            byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
+            long rdlen = 0; //This is the total number of bytes written. 
+            long totlen = fin.Length; //This is the total length of the input file. 
+            int len; //This is the number of bytes to be written at a time. 
+
+            DES des = new DESCryptoServiceProvider();
+            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
+
+            //Read from the input file, then encrypt and write to the output file. 
+            while (rdlen < totlen)
+            {
+                len = fin.Read(bin, 0, 100);
+                encStream.Write(bin, 0, len);
+                rdlen += len;
+            }
+            encStream.Close();
+            fout.Close();
+            fin.Close();
+        }
+
+        /// <summary> 
+        /// Decrypt files 
+        /// Attention:key must be 8 bits 
+        /// </summary> 
+        /// <param name="m_InFilePath">Decrypt filepath</param> 
+        /// <param name="m_OutFilePath">output filepath</param> 
+        /// <param name="sDecrKey">key</param> 
+        public static void DesDecrypt(string m_InFilePath, string m_OutFilePath, string sDecrKey)
+        {
+            byte[] byKey = null;
+            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
+
+            byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
+            FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
+            FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
+            fout.SetLength(0);
+            //Create variables to help with read and write. 
+            byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
+            long rdlen = 0; //This is the total number of bytes written. 
+            long totlen = fin.Length; //This is the total length of the input file. 
+            int len; //This is the number of bytes to be written at a time. 
+
+            DES des = new DESCryptoServiceProvider();
+            CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
+
+            //Read from the input file, then encrypt and write to the output file. 
+            while (rdlen < totlen)
+            {
+                len = fin.Read(bin, 0, 100);
+                encStream.Write(bin, 0, len);
+                rdlen += len;
+            }
+            encStream.Close();
+            fout.Close();
+            fin.Close();
+        }
+        #endregion
+
+        #region 对称加密算法AES RijndaelManaged加密解密
+        private static readonly string Default_AES_Key = "@#kim123";
+        private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,
+                                             0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
+
+        /// <summary>
+        /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
+        /// </summary>
+        /// <param name="encryptString">待加密字符串</param>
+        /// <returns>加密结果字符串</returns>
+        public static string AES_Encrypt(string encryptString)
+        {
+            return AES_Encrypt(encryptString, Default_AES_Key);
+        }
+
+        /// <summary>
+        /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
+        /// </summary>
+        /// <param name="encryptString">待加密字符串</param>
+        /// <param name="encryptKey">加密密钥,须半角字符</param>
+        /// <returns>加密结果字符串</returns>
+        public static string AES_Encrypt(string encryptString, string encryptKey)
+        {
+            encryptKey = GetSubString(encryptKey, 32, "");
+            encryptKey = encryptKey.PadRight(32, ' ');
+
+            RijndaelManaged rijndaelProvider = new RijndaelManaged();
+            rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
+            rijndaelProvider.IV = Keys;
+            ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
+
+            byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
+            byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
+
+            return Convert.ToBase64String(encryptedData);
+        }
+
+        /// <summary>
+        /// 对称加密算法AES RijndaelManaged解密字符串
+        /// </summary>
+        /// <param name="decryptString">待解密的字符串</param>
+        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
+        public static string AES_Decrypt(string decryptString)
+        {
+            return AES_Decrypt(decryptString, Default_AES_Key);
+        }
+
+        /// <summary>
+        /// 对称加密算法AES RijndaelManaged解密字符串
+        /// </summary>
+        /// <param name="decryptString">待解密的字符串</param>
+        /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
+        /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
+        public static string AES_Decrypt(string decryptString, string decryptKey)
+        {
+            try
+            {
+                decryptKey = GetSubString(decryptKey, 32, "");
+                decryptKey = decryptKey.PadRight(32, ' ');
+
+                RijndaelManaged rijndaelProvider = new RijndaelManaged();
+                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
+                rijndaelProvider.IV = Keys;
+                ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
+
+                byte[] inputData = Convert.FromBase64String(decryptString);
+                byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
+
+                return Encoding.UTF8.GetString(decryptedData);
+            }
+            catch
+            {
+                return string.Empty;
+            }
+        }
+
+        /// <summary>
+        /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
+        /// </summary>
+        /// <param name="sourceString">源字符串</param>
+        /// <param name="length">所取字符串字节长度</param>
+        /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
+        /// <returns>某字符串的一部分</returns>
+        private static string GetSubString(string sourceString, int length, string tailString)
+        {
+            return GetSubString(sourceString, 0, length, tailString);
+        }
+
+        /// <summary>
+        /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
+        /// </summary>
+        /// <param name="sourceString">源字符串</param>
+        /// <param name="startIndex">索引位置,以0开始</param>
+        /// <param name="length">所取字符串字节长度</param>
+        /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
+        /// <returns>某字符串的一部分</returns>
+        private static string GetSubString(string sourceString, int startIndex, int length, string tailString)
+        {
+            string myResult = sourceString;
+
+            //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
+            if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
+            {
+                //当截取的起始位置超出字段串长度时
+                if (startIndex >= sourceString.Length)
+                {
+                    return string.Empty;
+                }
+                else
+                {
+                    return sourceString.Substring(startIndex,
+                                                   ((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length);
+                }
+            }
+
+            //中文字符,如"中国人民abcd123"
+            if (length <= 0)
+            {
+                return string.Empty;
+            }
+            byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
+
+            //当字符串长度大于起始位置
+            if (bytesSource.Length > startIndex)
+            {
+                int endIndex = bytesSource.Length;
+
+                //当要截取的长度在字符串的有效长度范围内
+                if (bytesSource.Length > (startIndex + length))
+                {
+                    endIndex = length + startIndex;
+                }
+                else
+                {   //当不在有效范围内时,只取到字符串的结尾
+                    length = bytesSource.Length - startIndex;
+                    tailString = "";
+                }
+
+                int[] anResultFlag = new int[length];
+                int nFlag = 0;
+                //字节大于127为双字节字符
+                for (int i = startIndex; i < endIndex; i++)
+                {
+                    if (bytesSource[i] > 127)
+                    {
+                        nFlag++;
+                        if (nFlag == 3)
+                        {
+                            nFlag = 1;
+                        }
+                    }
+                    else
+                    {
+                        nFlag = 0;
+                    }
+                    anResultFlag[i] = nFlag;
+                }
+                //最后一个字节为双字节字符的一半
+                if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
+                {
+                    length++;
+                }
+                byte[] bsResult = new byte[length];
+                Array.Copy(bytesSource, startIndex, bsResult, 0, length);
+                myResult = Encoding.Default.GetString(bsResult);
+                myResult += tailString;
+                return myResult;
+            }
+            return string.Empty;
+        }
+
+        /// <summary>
+        /// 加密文件流
+        /// </summary>
+        /// <param name="fs">需要加密的文件流</param>
+        /// <param name="decryptKey">加密密钥</param>
+        /// <returns>加密流</returns>
+        public static CryptoStream AES_EncryptStrream(this FileStream fs, string decryptKey)
+        {
+            decryptKey = GetSubString(decryptKey, 32, "");
+            decryptKey = decryptKey.PadRight(32, ' ');
+
+            RijndaelManaged rijndaelProvider = new RijndaelManaged();
+            rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
+            rijndaelProvider.IV = Keys;
+
+            ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
+            CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
+            return cytptostreamEncr;
+        }
+
+        /// <summary>
+        /// 解密文件流
+        /// </summary>
+        /// <param name="fs">需要解密的文件流</param>
+        /// <param name="decryptKey">解密密钥</param>
+        /// <returns>加密流</returns>
+        public static CryptoStream AES_DecryptStream(this FileStream fs, string decryptKey)
+        {
+            decryptKey = GetSubString(decryptKey, 32, "");
+            decryptKey = decryptKey.PadRight(32, ' ');
+
+            RijndaelManaged rijndaelProvider = new RijndaelManaged();
+            rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
+            rijndaelProvider.IV = Keys;
+            ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();
+            CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);
+            return cytptostreamDecr;
+        }
+
+        /// <summary>
+        /// 对指定文件加密
+        /// </summary>
+        /// <param name="InputFile">源文件</param>
+        /// <param name="OutputFile">输出文件</param>
+        /// <returns></returns>
+        public static bool AES_EncryptFile(string InputFile, string OutputFile)
+        {
+            try
+            {
+                string decryptKey = "www.masuit.com";
+                FileStream fr = new FileStream(InputFile, FileMode.Open);
+                FileStream fren = new FileStream(OutputFile, FileMode.Create);
+                CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);
+                byte[] bytearrayinput = new byte[fr.Length];
+                fr.Read(bytearrayinput, 0, bytearrayinput.Length);
+                Enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
+                Enfr.Close();
+                fr.Close();
+                fren.Close();
+            }
+            catch
+            {
+                //文件异常
+                return false;
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// 对指定的文件解压缩
+        /// </summary>
+        /// <param name="InputFile"></param>
+        /// <param name="OutputFile"></param>
+        /// <returns></returns>
+        public static bool AES_DecryptFile(string InputFile, string OutputFile)
+        {
+            try
+            {
+                string decryptKey = "www.masuit.com";
+                FileStream fr = new FileStream(InputFile, FileMode.Open);
+                FileStream frde = new FileStream(OutputFile, FileMode.Create);
+                CryptoStream Defr = AES_DecryptStream(fr, decryptKey);
+                byte[] bytearrayoutput = new byte[1024];
+                int m_count = 0;
+                while (true)
+                {
+                    m_count = Defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
+                    frde.Write(bytearrayoutput, 0, m_count);
+                    if (m_count < bytearrayoutput.Length)
+                        break;
+                }
+                Defr.Close();
+                fr.Close();
+                frde.Close();
+            }
+            catch
+            {
+                //文件异常
+                return false;
+            }
+            return true;
+        }
+
+        #endregion
+
+        #region Base64加密解密
+        /// <summary>
+        /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
+        /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
+        /// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
+        /// 系統中而不同。
+        /// Base64加密
+        /// </summary>
+        /// <param name="str"></param>
+        /// <returns></returns>
+        public static string Base64Encrypt(string str)
+        {
+            byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
+            return Convert.ToBase64String(encbuff);
+        }
+
+        /// <summary>
+        /// Base64解密
+        /// </summary>
+        /// <param name="str"></param>
+        /// <returns></returns>
+        public static string Base64Decrypt(string str)
+        {
+            byte[] decbuff = Convert.FromBase64String(str);
+            return System.Text.Encoding.UTF8.GetString(decbuff);
+        }
+        #endregion
+
+        #region MD5加密
+        /// <summary> 
+        /// MD5加密
+        /// </summary> 
+        /// <param name="strText">原数据</param> 
+        /// <returns>MD5字符串</returns> 
+        public static string MD5Encrypt(string strText)
+        {
+            MD5 md5 = new MD5CryptoServiceProvider();
+            byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(strText));
+            return Encoding.Default.GetString(result);
+        }
+
+        /// <summary>
+        /// MD5 三次加密算法.计算过程: (QQ使用)
+        /// 1. 验证码转为大写
+        /// 2. 将密码使用这个方法进行三次加密后,与验证码进行叠加
+        /// 3. 然后将叠加后的内容再次MD5一下,得到最终验证码的值
+        /// </summary>
+        /// <param name="s">需要加密的字符串</param>
+        /// <returns>MD5字符串</returns>
+        public static string EncyptMD5_3_16(string s)
+        {
+            MD5 md5 = MD5CryptoServiceProvider.Create();
+            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s);
+            byte[] bytes1 = md5.ComputeHash(bytes);
+            byte[] bytes2 = md5.ComputeHash(bytes1);
+            byte[] bytes3 = md5.ComputeHash(bytes2);
+
+            StringBuilder sb = new StringBuilder();
+            foreach (var item in bytes3)
+            {
+                sb.Append(item.ToString("x").PadLeft(2, '0'));
+            }
+            return sb.ToString().ToUpper();
+        }
+        #endregion
+
+        /// <summary>
+        /// SHA256函数
+        /// </summary>
+        /// <param name="str">原始字符串</param>
+        /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
+        public static string SHA256(string str)
+        {
+            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
+            SHA256Managed Sha256 = new SHA256Managed();
+            byte[] Result = Sha256.ComputeHash(SHA256Data);
+            return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
+        }
+    }
+}

+ 1053 - 0
Masuit.Tools/Security/Encrypt.cs

@@ -0,0 +1,1053 @@
+using System;
+using System.Collections;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Masuit.Tools.Security
+{
+    /// <summary>
+    /// 常用的加密解密算法
+    /// </summary>
+    public static class Encrypt
+    {
+        #region DES加密算法
+
+        /// <summary>
+        ///     DES加密算法
+        ///     sKey为8位或16位
+        /// </summary>
+        /// <param name="pToEncrypt">需要加密的字符串</param>
+        /// <param name="sKey">密钥</param>
+        /// <returns></returns>
+        public static string DesEncrypt(this string pToEncrypt, string sKey)
+        {
+            var des = new DESCryptoServiceProvider();
+            var inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
+            des.Key = Encoding.ASCII.GetBytes(sKey);
+            des.IV = Encoding.ASCII.GetBytes(sKey);
+            var ms = new MemoryStream();
+            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
+            cs.Write(inputByteArray, 0, inputByteArray.Length);
+            cs.FlushFinalBlock();
+            var ret = new StringBuilder();
+            foreach (var b in ms.ToArray())
+                ret.AppendFormat("{0:X2}", b);
+            return ret.ToString();
+        }
+
+        #endregion
+
+        #region DES解密算法
+
+        /// <summary>
+        ///     DES解密算法
+        ///     sKey为8位或16位
+        /// </summary>
+        /// <param name="pToDecrypt">需要解密的字符串</param>
+        /// <param name="sKey">密钥</param>
+        /// <returns></returns>
+        public static string DesDecrypt(this string pToDecrypt, string sKey)
+        {
+            var des = new DESCryptoServiceProvider();
+            var inputByteArray = new byte[pToDecrypt.Length / 2];
+            for (var x = 0; x < pToDecrypt.Length / 2; x++)
+            {
+                var i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
+                inputByteArray[x] = (byte)i;
+            }
+            des.Key = Encoding.ASCII.GetBytes(sKey);
+            des.IV = Encoding.ASCII.GetBytes(sKey);
+            var ms = new MemoryStream();
+            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
+            cs.Write(inputByteArray, 0, inputByteArray.Length);
+            cs.FlushFinalBlock();
+            var ret = new StringBuilder();
+            return Encoding.Default.GetString(ms.ToArray());
+        }
+
+        #endregion
+
+        #region 创建Key
+
+        /// <summary>
+        ///     创建Key
+        /// </summary>
+        /// <returns></returns>
+        public static string GenerateKey()
+        {
+            var desCrypto = (DESCryptoServiceProvider)DES.Create();
+            return Encoding.ASCII.GetString(desCrypto.Key);
+        }
+
+        #endregion
+
+        #region MD5加密
+
+        /// <summary>
+        ///     MD5加密
+        /// </summary>
+        /// <param name="pToEncrypt">加密字符串</param>
+        /// <param name="sKey">密钥Key</param>
+        /// <returns></returns>
+        public static string MD5Encrypt(this string pToEncrypt, string sKey)
+        {
+            var des = new DESCryptoServiceProvider();
+            var inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
+            des.Key = Encoding.ASCII.GetBytes(sKey);
+            des.IV = Encoding.ASCII.GetBytes(sKey);
+            var ms = new MemoryStream();
+            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
+            cs.Write(inputByteArray, 0, inputByteArray.Length);
+            cs.FlushFinalBlock();
+            var ret = new StringBuilder();
+            foreach (var b in ms.ToArray())
+                ret.AppendFormat("{0:X2}", b);
+            ret.ToString();
+            return ret.ToString();
+        }
+
+        #endregion
+
+        #region MD5解密
+
+        /// <summary>
+        ///     MD5解密
+        /// </summary>
+        /// <param name="pToDecrypt">解密字符串</param>
+        /// <param name="sKey">密钥Key</param>
+        /// <returns></returns>
+        public static string MD5Decrypt(this string pToDecrypt, string sKey)
+        {
+            var des = new DESCryptoServiceProvider();
+
+            var inputByteArray = new byte[pToDecrypt.Length / 2];
+            for (var x = 0; x < pToDecrypt.Length / 2; x++)
+            {
+                var i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
+                inputByteArray[x] = (byte)i;
+            }
+
+            des.Key = Encoding.ASCII.GetBytes(sKey);
+            des.IV = Encoding.ASCII.GetBytes(sKey);
+            var ms = new MemoryStream();
+            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
+            cs.Write(inputByteArray, 0, inputByteArray.Length);
+            cs.FlushFinalBlock();
+
+            var ret = new StringBuilder();
+
+            return Encoding.Default.GetString(ms.ToArray());
+        }
+
+        #endregion
+
+        #region MD5加密算法
+
+        //number of bits to rotate in tranforming
+        private const int S11 = 7;
+
+        private const int S12 = 12;
+        private const int S13 = 17;
+        private const int S14 = 22;
+        private const int S21 = 5;
+        private const int S22 = 9;
+        private const int S23 = 14;
+        private const int S24 = 20;
+        private const int S31 = 4;
+        private const int S32 = 11;
+        private const int S33 = 16;
+        private const int S34 = 23;
+        private const int S41 = 6;
+        private const int S42 = 10;
+        private const int S43 = 15;
+        private const int S44 = 21;
+
+        //static state variables
+        private static uint A;
+
+        private static uint B;
+        private static uint C;
+        private static uint D;
+
+        private static uint F(uint x, uint y, uint z)
+        {
+            return (x & y) | (~x & z);
+        }
+
+        private static uint G(uint x, uint y, uint z)
+        {
+            return (x & z) | (y & ~z);
+        }
+
+        private static uint H(uint x, uint y, uint z)
+        {
+            return x ^ y ^ z;
+        }
+
+        private static uint I(uint x, uint y, uint z)
+        {
+            return y ^ (x | ~z);
+        }
+
+        private static void FF(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
+        {
+            a = a + F(b, c, d) + mj + ti;
+            a = (a << s) | (a >> (32 - s));
+            a += b;
+        }
+
+        private static void GG(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
+        {
+            a = a + G(b, c, d) + mj + ti;
+            a = (a << s) | (a >> (32 - s));
+            a += b;
+        }
+
+        private static void HH(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
+        {
+            a = a + H(b, c, d) + mj + ti;
+            a = (a << s) | (a >> (32 - s));
+            a += b;
+        }
+
+        private static void II(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
+        {
+            a = a + I(b, c, d) + mj + ti;
+            a = (a << s) | (a >> (32 - s));
+            a += b;
+        }
+
+        private static void MD5_Init()
+        {
+            A = 0x67452301; //in memory, this is 0x01234567
+            B = 0xefcdab89; //in memory, this is 0x89abcdef
+            C = 0x98badcfe; //in memory, this is 0xfedcba98
+            D = 0x10325476; //in memory, this is 0x76543210
+        }
+
+        private static uint[] MD5_Append(byte[] input)
+        {
+            var zeros = 0;
+            var ones = 1;
+            var size = 0;
+            var n = input.Length;
+            var m = n % 64;
+            if (m < 56)
+            {
+                zeros = 55 - m;
+                size = n - m + 64;
+            }
+            else if (m == 56)
+            {
+                zeros = 0;
+                ones = 0;
+                size = n + 8;
+            }
+            else
+            {
+                zeros = 63 - m + 56;
+                size = n + 64 - m + 64;
+            }
+
+            var bs = new ArrayList(input);
+            if (ones == 1)
+                bs.Add((byte)0x80); // 0x80 = $10000000
+            for (var i = 0; i < zeros; i++)
+                bs.Add((byte)0);
+
+            var N = (ulong)n * 8;
+            var h1 = (byte)(N & 0xFF);
+            var h2 = (byte)((N >> 8) & 0xFF);
+            var h3 = (byte)((N >> 16) & 0xFF);
+            var h4 = (byte)((N >> 24) & 0xFF);
+            var h5 = (byte)((N >> 32) & 0xFF);
+            var h6 = (byte)((N >> 40) & 0xFF);
+            var h7 = (byte)((N >> 48) & 0xFF);
+            var h8 = (byte)(N >> 56);
+            bs.Add(h1);
+            bs.Add(h2);
+            bs.Add(h3);
+            bs.Add(h4);
+            bs.Add(h5);
+            bs.Add(h6);
+            bs.Add(h7);
+            bs.Add(h8);
+            var ts = (byte[])bs.ToArray(typeof(byte));
+
+            /* Decodes input (byte[]) into output (UInt32[]). Assumes len is
+            * a multiple of 4.
+           */
+            var output = new uint[size / 4];
+            for (long i = 0, j = 0; i < size; j++, i += 4)
+                output[j] = (uint)(ts[i] | (ts[i + 1] << 8) | (ts[i + 2] << 16) | (ts[i + 3] << 24));
+            return output;
+        }
+
+        private static uint[] MD5_Trasform(uint[] x)
+        {
+            uint a, b, c, d;
+
+            for (var k = 0; k < x.Length; k += 16)
+            {
+                a = A;
+                b = B;
+                c = C;
+                d = D;
+
+                /* Round 1 */
+                FF(ref a, b, c, d, x[k + 0], S11, 0xd76aa478); /* 1 */
+                FF(ref d, a, b, c, x[k + 1], S12, 0xe8c7b756); /* 2 */
+                FF(ref c, d, a, b, x[k + 2], S13, 0x242070db); /* 3 */
+                FF(ref b, c, d, a, x[k + 3], S14, 0xc1bdceee); /* 4 */
+                FF(ref a, b, c, d, x[k + 4], S11, 0xf57c0faf); /* 5 */
+                FF(ref d, a, b, c, x[k + 5], S12, 0x4787c62a); /* 6 */
+                FF(ref c, d, a, b, x[k + 6], S13, 0xa8304613); /* 7 */
+                FF(ref b, c, d, a, x[k + 7], S14, 0xfd469501); /* 8 */
+                FF(ref a, b, c, d, x[k + 8], S11, 0x698098d8); /* 9 */
+                FF(ref d, a, b, c, x[k + 9], S12, 0x8b44f7af); /* 10 */
+                FF(ref c, d, a, b, x[k + 10], S13, 0xffff5bb1); /* 11 */
+                FF(ref b, c, d, a, x[k + 11], S14, 0x895cd7be); /* 12 */
+                FF(ref a, b, c, d, x[k + 12], S11, 0x6b901122); /* 13 */
+                FF(ref d, a, b, c, x[k + 13], S12, 0xfd987193); /* 14 */
+                FF(ref c, d, a, b, x[k + 14], S13, 0xa679438e); /* 15 */
+                FF(ref b, c, d, a, x[k + 15], S14, 0x49b40821); /* 16 */
+
+                /* Round 2 */
+                GG(ref a, b, c, d, x[k + 1], S21, 0xf61e2562); /* 17 */
+                GG(ref d, a, b, c, x[k + 6], S22, 0xc040b340); /* 18 */
+                GG(ref c, d, a, b, x[k + 11], S23, 0x265e5a51); /* 19 */
+                GG(ref b, c, d, a, x[k + 0], S24, 0xe9b6c7aa); /* 20 */
+                GG(ref a, b, c, d, x[k + 5], S21, 0xd62f105d); /* 21 */
+                GG(ref d, a, b, c, x[k + 10], S22, 0x2441453); /* 22 */
+                GG(ref c, d, a, b, x[k + 15], S23, 0xd8a1e681); /* 23 */
+                GG(ref b, c, d, a, x[k + 4], S24, 0xe7d3fbc8); /* 24 */
+                GG(ref a, b, c, d, x[k + 9], S21, 0x21e1cde6); /* 25 */
+                GG(ref d, a, b, c, x[k + 14], S22, 0xc33707d6); /* 26 */
+                GG(ref c, d, a, b, x[k + 3], S23, 0xf4d50d87); /* 27 */
+                GG(ref b, c, d, a, x[k + 8], S24, 0x455a14ed); /* 28 */
+                GG(ref a, b, c, d, x[k + 13], S21, 0xa9e3e905); /* 29 */
+                GG(ref d, a, b, c, x[k + 2], S22, 0xfcefa3f8); /* 30 */
+                GG(ref c, d, a, b, x[k + 7], S23, 0x676f02d9); /* 31 */
+                GG(ref b, c, d, a, x[k + 12], S24, 0x8d2a4c8a); /* 32 */
+
+                /* Round 3 */
+                HH(ref a, b, c, d, x[k + 5], S31, 0xfffa3942); /* 33 */
+                HH(ref d, a, b, c, x[k + 8], S32, 0x8771f681); /* 34 */
+                HH(ref c, d, a, b, x[k + 11], S33, 0x6d9d6122); /* 35 */
+                HH(ref b, c, d, a, x[k + 14], S34, 0xfde5380c); /* 36 */
+                HH(ref a, b, c, d, x[k + 1], S31, 0xa4beea44); /* 37 */
+                HH(ref d, a, b, c, x[k + 4], S32, 0x4bdecfa9); /* 38 */
+                HH(ref c, d, a, b, x[k + 7], S33, 0xf6bb4b60); /* 39 */
+                HH(ref b, c, d, a, x[k + 10], S34, 0xbebfbc70); /* 40 */
+                HH(ref a, b, c, d, x[k + 13], S31, 0x289b7ec6); /* 41 */
+                HH(ref d, a, b, c, x[k + 0], S32, 0xeaa127fa); /* 42 */
+                HH(ref c, d, a, b, x[k + 3], S33, 0xd4ef3085); /* 43 */
+                HH(ref b, c, d, a, x[k + 6], S34, 0x4881d05); /* 44 */
+                HH(ref a, b, c, d, x[k + 9], S31, 0xd9d4d039); /* 45 */
+                HH(ref d, a, b, c, x[k + 12], S32, 0xe6db99e5); /* 46 */
+                HH(ref c, d, a, b, x[k + 15], S33, 0x1fa27cf8); /* 47 */
+                HH(ref b, c, d, a, x[k + 2], S34, 0xc4ac5665); /* 48 */
+
+                /* Round 4 */
+                II(ref a, b, c, d, x[k + 0], S41, 0xf4292244); /* 49 */
+                II(ref d, a, b, c, x[k + 7], S42, 0x432aff97); /* 50 */
+                II(ref c, d, a, b, x[k + 14], S43, 0xab9423a7); /* 51 */
+                II(ref b, c, d, a, x[k + 5], S44, 0xfc93a039); /* 52 */
+                II(ref a, b, c, d, x[k + 12], S41, 0x655b59c3); /* 53 */
+                II(ref d, a, b, c, x[k + 3], S42, 0x8f0ccc92); /* 54 */
+                II(ref c, d, a, b, x[k + 10], S43, 0xffeff47d); /* 55 */
+                II(ref b, c, d, a, x[k + 1], S44, 0x85845dd1); /* 56 */
+                II(ref a, b, c, d, x[k + 8], S41, 0x6fa87e4f); /* 57 */
+                II(ref d, a, b, c, x[k + 15], S42, 0xfe2ce6e0); /* 58 */
+                II(ref c, d, a, b, x[k + 6], S43, 0xa3014314); /* 59 */
+                II(ref b, c, d, a, x[k + 13], S44, 0x4e0811a1); /* 60 */
+                II(ref a, b, c, d, x[k + 4], S41, 0xf7537e82); /* 61 */
+                II(ref d, a, b, c, x[k + 11], S42, 0xbd3af235); /* 62 */
+                II(ref c, d, a, b, x[k + 2], S43, 0x2ad7d2bb); /* 63 */
+                II(ref b, c, d, a, x[k + 9], S44, 0xeb86d391); /* 64 */
+
+                A += a;
+                B += b;
+                C += c;
+                D += d;
+            }
+            return new[] { A, B, C, D };
+        }
+
+        #region MD5对数组数据加密
+
+        /// <summary>
+        ///     MD5对数组数据加密
+        /// </summary>
+        /// <param name="input">包含需要加密的数据的数组</param>
+        /// <returns></returns>
+        public static byte[] MD5Array(this byte[] input)
+        {
+            MD5_Init();
+            var block = MD5_Append(input);
+            var bits = MD5_Trasform(block);
+
+            var output = new byte[bits.Length * 4];
+            for (int i = 0, j = 0; i < bits.Length; i++, j += 4)
+            {
+                output[j] = (byte)(bits[i] & 0xff);
+                output[j + 1] = (byte)((bits[i] >> 8) & 0xff);
+                output[j + 2] = (byte)((bits[i] >> 16) & 0xff);
+                output[j + 3] = (byte)((bits[i] >> 24) & 0xff);
+            }
+            return output;
+        }
+
+        #endregion
+
+        #region 获取数组的Hex值
+
+        /// <summary>
+        ///     获取数组的Hex值
+        /// </summary>
+        /// <param name="array">需要求Hex值的数组</param>
+        /// <param name="uppercase"></param>
+        /// <returns></returns>
+        public static string ArrayToHexString(this byte[] array, bool uppercase)
+        {
+            var hexString = "";
+            var format = "x2";
+            if (uppercase)
+                format = "X2";
+            foreach (var b in array)
+                hexString += b.ToString(format);
+            return hexString;
+        }
+
+        #endregion
+
+        #region 对字符串进行MD5加密
+
+        /// <summary>
+        ///     对字符串进行MD5加密
+        /// </summary>
+        /// <param name="message">需要加密的字符串</param>
+        /// <returns></returns>
+        public static string MDString(this string message)
+        {
+            var c = message.ToCharArray();
+            var b = new byte[c.Length];
+            for (var i = 0; i < c.Length; i++)
+                b[i] = (byte)c[i];
+            var digest = MD5Array(b);
+            return ArrayToHexString(digest, false);
+        }
+
+        #endregion
+
+        #region 获取文件的MD5值
+
+        /// <summary>
+        /// 获取文件的MD5值
+        /// </summary>
+        /// <param name="fileName">需要求MD5值的文件的文件名及路径</param>
+        /// <returns></returns>
+        public static string MDFile(this string fileName)
+        {
+            var fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
+            var array = new byte[fs.Length];
+            fs.Read(array, 0, (int)fs.Length);
+            var digest = MD5Array(array);
+            fs.Close();
+            return ArrayToHexString(digest, false);
+        }
+
+        #endregion
+
+        #region 测试MD5加密算法的函数
+
+        /// <summary>
+        ///     测试MD5加密算法的函数
+        /// </summary>
+        /// <param name="message">需要加密的字符串</param>
+        /// <returns></returns>
+        private static string MD5Test(this string message)
+        {
+            return "rnMD5 (" + "message" + ") = " + MDString(message);
+        }
+
+        #endregion
+
+        #region MD5加密算法测试用数据
+
+        /// <summary>
+        ///     MD5加密算法测试用数据
+        /// </summary>
+        /// <returns></returns>
+        private static string TestSuite()
+        {
+            var s = "";
+            s += MD5Test("");
+            s += MD5Test("a");
+            s += MD5Test("abc");
+            s += MD5Test("message digest");
+            s += MD5Test("abcdefghijklmnopqrstuvwxyz");
+            s += MD5Test("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
+            s += MD5Test("12345678901234567890123456789012345678901234567890123456789012345678901234567890");
+            return s;
+        }
+
+        #endregion
+
+        #endregion MD5加密算法
+    }
+
+    /// <summary>
+    ///     RC2加密解密算法
+    /// </summary>
+    public static class RC2
+    {
+        private static ASCIIEncoding asciiEncoding;
+        private static byte[] iv;
+        private static byte[] key;
+        private static RC2CryptoServiceProvider rc2CSP;
+        private static UnicodeEncoding textConverter;
+
+        static RC2()
+        {
+            InitializeComponent();
+        }
+
+        private static void InitializeComponent()
+        {
+            key = new byte[] { 106, 51, 25, 141, 157, 142, 23, 111, 234, 159, 187, 154, 215, 34, 37, 204 };
+            iv = new byte[] { 135, 186, 133, 136, 184, 149, 153, 144 };
+            asciiEncoding = new ASCIIEncoding();
+            textConverter = new UnicodeEncoding();
+            rc2CSP = new RC2CryptoServiceProvider();
+        }
+
+        #region 新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
+
+        /// <summary>
+        ///     新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
+        /// </summary>
+        /// <param name="filePath">文件保存的地址,包含文件名</param>
+        public static string InitBinFile(this string filePath)
+        {
+            var tmp = new byte[10261];
+            try //创建文件流,将其内容全部写入0
+            {
+                var writeFileStream = new FileStream(filePath,
+                    FileMode.Create,
+                    FileAccess.Write,
+                    FileShare.None, 512, false);
+
+                for (var i = 0; i < 10261; i++)
+                    tmp[i] = 0;
+                writeFileStream.Write(tmp, 0, 10261);
+                writeFileStream.Flush();
+                writeFileStream.Close();
+            }
+            catch (IOException)
+            {
+                // MessageBox.Show("文件操作错误!", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
+                return "Error,file operation error!";
+            }
+            return "OK";
+        }
+
+        #endregion
+
+        #region 将文本数据加密后写入一个文件
+
+        /// <summary>
+        ///     将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
+        ///     用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
+        ///     一个byte的取值为0-127,所以,用两个byte来存放一个长度。
+        /// </summary>
+        /// <param name="toEncryptText">要加密的文本数据</param>
+        /// <param name="filePath">要写入的文件</param>
+        /// <param name="dataIndex">写入第几块,取值为1--10</param>
+        /// <returns>是否操作成功</returns>
+        public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex)
+        {
+            var r = false;
+            if ((dataIndex > 10) && (dataIndex < 1))
+                return r;
+            byte[] encrypted;
+            //打开要写入的文件,主要是为了保持原文件的内容不丢失
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.Open,
+                FileAccess.Read,
+                FileShare.None, 1024, true);
+
+            var index = new byte[10261];
+            //将读取的内容写到byte数组
+            tmpFileStream.Read(index, 0, 10261);
+            tmpFileStream.Close();
+            //定义基本的加密转换运算
+            var Encryptor = rc2CSP.CreateEncryptor(key, iv);
+            var msEncrypt = new MemoryStream();
+            //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
+            var csEncrypt = new CryptoStream(msEncrypt,
+                Encryptor, CryptoStreamMode.Write);
+            //将要加密的文本转换成UTF-16 编码,保存在tmp数组。
+            var tmp = textConverter.GetBytes(toEncryptText);
+            //将tmp输入csEncrypt,将通过Encryptor来加密。
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            //输出到msEnctypt
+            csEncrypt.FlushFinalBlock();
+            //将流转成byte[]
+            encrypted = msEncrypt.ToArray();
+            if (encrypted.Length > 1024)
+                return false;
+            //得到加密后数据的大小,将结果存在指定的位置。
+            index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
+            index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
+            //将加密后的结果写入index(覆盖)
+            for (var i = 0; i < encrypted.Length; i++)
+                index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
+            //建立文件流
+            tmpFileStream = new FileStream(filePath,
+                FileMode.Truncate,
+                FileAccess.Write,
+                FileShare.None, 1024, true);
+            //写文件
+            tmpFileStream.Write(index, 0, 10261);
+            tmpFileStream.Flush();
+            r = true;
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
+
+        /// <summary>
+        ///     从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
+        /// </summary>
+        /// <param name="filePath">要解密的文件</param>
+        /// <param name="dataIndex">要从哪一个块中解密</param>
+        /// <returns>解密后的文本</returns>
+        public static string DecryptFromFile(string filePath, int dataIndex)
+        {
+            var r = "";
+            if ((dataIndex > 10) && (dataIndex < 1))
+                return r;
+            byte[] decrypted;
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.Open,
+                FileAccess.Read,
+                FileShare.None, 1024, true);
+
+            var Decryptor = rc2CSP.CreateDecryptor(key, iv);
+            var msDecrypt = new MemoryStream();
+            var csDecrypt = new CryptoStream(msDecrypt,
+                Decryptor, CryptoStreamMode.Write);
+            var index = new byte[10261];
+
+            tmpFileStream.Read(index, 0, 10261);
+            var startIndex = 1024 * (dataIndex - 1) + 21;
+            var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
+            var tmp = new byte[count];
+
+            Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
+            csDecrypt.Write(tmp, 0, count);
+            csDecrypt.FlushFinalBlock();
+            decrypted = msDecrypt.ToArray();
+            r = textConverter.GetString(decrypted, 0, decrypted.Length);
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 将一段文本加密后保存到一个文件
+
+        /// <summary>
+        ///     将一段文本加密后保存到一个文件
+        /// </summary>
+        /// <param name="toEncryptText">要加密的文本数据</param>
+        /// <param name="filePath">要保存的文件</param>
+        /// <returns>是否加密成功</returns>
+        public static bool EncryptToFile(this string toEncryptText, string filePath)
+        {
+            var r = false;
+            byte[] encrypted;
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.OpenOrCreate,
+                FileAccess.Write,
+                FileShare.None, 1024, true);
+
+            var Encryptor = rc2CSP.CreateEncryptor(key, iv);
+            var msEncrypt = new MemoryStream();
+            var csEncrypt = new CryptoStream(msEncrypt,
+                Encryptor, CryptoStreamMode.Write);
+
+            var tmp = textConverter.GetBytes(toEncryptText);
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            csEncrypt.FlushFinalBlock();
+            encrypted = msEncrypt.ToArray();
+            tmpFileStream.Write(encrypted, 0, encrypted.Length);
+            tmpFileStream.Flush();
+            r = true;
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 将一个被加密的文件解密
+
+        /// <summary>
+        ///     将一个被加密的文件解密
+        /// </summary>
+        /// <param name="filePath">要解密的文件</param>
+        /// <returns>解密后的文本</returns>
+        public static string DecryptFromFile(string filePath)
+        {
+            var r = "";
+            byte[] decrypted;
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.Open,
+                FileAccess.Read,
+                FileShare.None, 1024, true);
+            var Decryptor = rc2CSP.CreateDecryptor(key, iv);
+            var msDecrypt = new MemoryStream();
+            var csDecrypt = new CryptoStream(msDecrypt,
+                Decryptor, CryptoStreamMode.Write);
+
+            var tmp = new byte[tmpFileStream.Length];
+            tmpFileStream.Read(tmp, 0, tmp.Length);
+            csDecrypt.Write(tmp, 0, tmp.Length);
+            csDecrypt.FlushFinalBlock();
+            decrypted = msDecrypt.ToArray();
+            r = textConverter.GetString(decrypted, 0, decrypted.Length);
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 将文本数据加密后写入一个文件
+
+        /// <summary>
+        ///     将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
+        ///     用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
+        ///     一个byte的取值为0-127,所以,用两个byte来存放一个长度。
+        /// </summary>
+        /// <param name="toEncryptText">要加密的文本数据</param>
+        /// <param name="filePath">要写入的文件</param>
+        /// <param name="dataIndex">写入第几块,取值为1--10</param>
+        /// <param name="IV">初始化向量</param>
+        /// <param name="Key">加密密匙</param>
+        /// <returns>是否操作成功</returns>
+        public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
+        {
+            var r = false;
+            if ((dataIndex > 10) && (dataIndex < 1))
+                return r;
+            byte[] encrypted;
+            //打开要写入的文件,主要是为了保持原文件的内容不丢失
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.Open,
+                FileAccess.Read,
+                FileShare.None, 1024, true);
+
+            var index = new byte[10261];
+            //将读取的内容写到byte数组
+            tmpFileStream.Read(index, 0, 10261);
+            tmpFileStream.Close();
+            //定义基本的加密转换运算
+            var Encryptor = rc2CSP.CreateEncryptor(Key, IV);
+            var msEncrypt = new MemoryStream();
+            //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
+            var csEncrypt = new CryptoStream(msEncrypt,
+                Encryptor, CryptoStreamMode.Write);
+            //将要加密的文本转换成UTF-16 编码,保存在tmp数组。
+            var tmp = textConverter.GetBytes(toEncryptText);
+            //将tmp输入csEncrypt,将通过Encryptor来加密。
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            //输出到msEnctypt
+            csEncrypt.FlushFinalBlock();
+            //将流转成byte[]
+            encrypted = msEncrypt.ToArray();
+            if (encrypted.Length > 1024)
+                return false;
+            //得到加密后数据的大小,将结果存在指定的位置。
+            index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
+            index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
+            //将加密后的结果写入index(覆盖)
+            for (var i = 0; i < encrypted.Length; i++)
+                index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
+            //建立文件流
+            tmpFileStream = new FileStream(filePath,
+                FileMode.Truncate,
+                FileAccess.Write,
+                FileShare.None, 1024, true);
+            //写文件
+            tmpFileStream.Write(index, 0, 10261);
+            tmpFileStream.Flush();
+            r = true;
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 从一个文件中解密出一段文本
+
+        /// <summary>
+        ///     从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
+        /// </summary>
+        /// <param name="filePath">要解密的文件</param>
+        /// <param name="dataIndex">要从哪一个块中解密</param>
+        /// <param name="IV">初始化向量</param>
+        /// <param name="Key">解密密匙</param>
+        /// <returns>解密后的文本</returns>
+        public static string DecryptFromFile(string filePath, int dataIndex, byte[] IV, byte[] Key)
+        {
+            var r = "";
+            if ((dataIndex > 10) && (dataIndex < 1))
+                return r;
+            byte[] decrypted;
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.Open,
+                FileAccess.Read,
+                FileShare.None, 1024, true);
+
+            var Decryptor = rc2CSP.CreateDecryptor(Key, IV);
+            var msDecrypt = new MemoryStream();
+            var csDecrypt = new CryptoStream(msDecrypt,
+                Decryptor, CryptoStreamMode.Write);
+            var index = new byte[10261];
+
+            tmpFileStream.Read(index, 0, 10261);
+            var startIndex = 1024 * (dataIndex - 1) + 21;
+            var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
+            var tmp = new byte[count];
+
+            Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
+            csDecrypt.Write(tmp, 0, count);
+            csDecrypt.FlushFinalBlock();
+            decrypted = msDecrypt.ToArray();
+            r = textConverter.GetString(decrypted, 0, decrypted.Length);
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 将一段文本加密后保存到一个文件
+
+        /// <summary>
+        ///     将一段文本加密后保存到一个文件
+        /// </summary>
+        /// <param name="toEncryptText">要加密的文本数据</param>
+        /// <param name="filePath">要保存的文件</param>
+        /// <param name="IV">初始化向量</param>
+        /// <param name="Key">加密密匙</param>
+        /// <returns>是否加密成功</returns>
+        public static bool EncryptToFile(this string toEncryptText, string filePath, byte[] IV, byte[] Key)
+        {
+            var r = false;
+            byte[] encrypted;
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.OpenOrCreate,
+                FileAccess.Write,
+                FileShare.None, 1024, true);
+
+            var Encryptor = rc2CSP.CreateEncryptor(Key, IV);
+            var msEncrypt = new MemoryStream();
+            var csEncrypt = new CryptoStream(msEncrypt,
+                Encryptor, CryptoStreamMode.Write);
+
+            var tmp = textConverter.GetBytes(toEncryptText);
+            csEncrypt.Write(tmp, 0, tmp.Length);
+            csEncrypt.FlushFinalBlock();
+            encrypted = msEncrypt.ToArray();
+            tmpFileStream.Write(encrypted, 0, encrypted.Length);
+            tmpFileStream.Flush();
+            r = true;
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 将一个被加密的文件解密
+
+        /// <summary>
+        ///     将一个被加密的文件解密
+        /// </summary>
+        /// <param name="filePath">要解密的文件</param>
+        /// <param name="IV">初始化向量</param>
+        /// <param name="Key">解密密匙</param>
+        /// <returns>解密后的文本</returns>
+        public static string DecryptFromFile(string filePath, byte[] IV, byte[] Key)
+        {
+            var r = "";
+            byte[] decrypted;
+            var tmpFileStream = new FileStream(filePath,
+                FileMode.Open,
+                FileAccess.Read,
+                FileShare.None, 1024, true);
+            var Decryptor = rc2CSP.CreateDecryptor(Key, IV);
+            var msDecrypt = new MemoryStream();
+            var csDecrypt = new CryptoStream(msDecrypt,
+                Decryptor, CryptoStreamMode.Write);
+
+            var tmp = new byte[tmpFileStream.Length];
+            tmpFileStream.Read(tmp, 0, tmp.Length);
+            csDecrypt.Write(tmp, 0, tmp.Length);
+            csDecrypt.FlushFinalBlock();
+            decrypted = msDecrypt.ToArray();
+            r = textConverter.GetString(decrypted, 0, decrypted.Length);
+            tmpFileStream.Close();
+            return r;
+        }
+
+        #endregion
+
+        #region 设置加密或解密的初始化向量
+
+        /// <summary>
+        ///     设置加密或解密的初始化向量
+        /// </summary>
+        /// <param name="s">长度等于8的ASCII字符集的字符串</param>
+        public static void SetIV(string s)
+        {
+            if (s.Length != 8)
+            {
+                // MessageBox.Show("输入的字符串必须为长度为8的且属于ASCII字符集的字符串");
+                iv = null;
+                return;
+            }
+            try
+            {
+                iv = asciiEncoding.GetBytes(s);
+            }
+            catch (Exception)
+            {
+                // MessageBox.Show("输入的字符串必须为长度为8的且属于ASCII字符集的字符串");
+                iv = null;
+            }
+        }
+
+        #endregion
+
+        #region 设置加密或解密的密匙
+
+        /// <summary>
+        ///     设置加密或解密的密匙
+        /// </summary>
+        /// <param name="s">长度等于16的ASCII字符集的字符串</param>
+        public static void SetKey(string s)
+        {
+            if (s.Length != 16)
+            {
+                // MessageBox.Show("输入的字符串必须为长度为16的且属于ASCII字符集的字符串");
+                key = null;
+                return;
+            }
+            try
+            {
+                key = asciiEncoding.GetBytes(s);
+            }
+            catch (Exception)
+            {
+                //MessageBox.Show("输入的字符串必须为长度为16的且属于ASCII字符集的字符串");
+                key = null;
+            }
+        }
+
+        #endregion
+    }
+
+    /// <summary>
+    ///     对称加密解密算法类
+    /// </summary>
+    public static class Rijndael
+    {
+        private static string Key;
+        private static SymmetricAlgorithm mobjCryptoService;
+
+        /// <summary>
+        ///     对称加密类的构造函数
+        /// </summary>
+        public static void SymmetricMethod()
+        {
+            mobjCryptoService = new RijndaelManaged();
+            Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
+        }
+
+        /// <summary>
+        ///     获得密钥
+        /// </summary>
+        /// <returns>密钥</returns>
+        private static byte[] GetLegalKey()
+        {
+            var sTemp = Key;
+            mobjCryptoService.GenerateKey();
+            var bytTemp = mobjCryptoService.Key;
+            var KeyLength = bytTemp.Length;
+            if (sTemp.Length > KeyLength)
+                sTemp = sTemp.Substring(0, KeyLength);
+            else if (sTemp.Length < KeyLength)
+                sTemp = sTemp.PadRight(KeyLength, ' ');
+            return Encoding.ASCII.GetBytes(sTemp);
+        }
+
+        /// <summary>
+        ///     获得初始向量IV
+        /// </summary>
+        /// <returns>初试向量IV</returns>
+        private static byte[] GetLegalIV()
+        {
+            var sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUber57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
+            mobjCryptoService.GenerateIV();
+            var bytTemp = mobjCryptoService.IV;
+            var IVLength = bytTemp.Length;
+            if (sTemp.Length > IVLength)
+                sTemp = sTemp.Substring(0, IVLength);
+            else if (sTemp.Length < IVLength)
+                sTemp = sTemp.PadRight(IVLength, ' ');
+            return Encoding.ASCII.GetBytes(sTemp);
+        }
+
+        /// <summary>
+        ///     加密方法
+        /// </summary>
+        /// <param name="Source">待加密的串</param>
+        /// <returns>经过加密的串</returns>
+        public static string Encrypto(this string Source)
+        {
+            var bytIn = Encoding.UTF8.GetBytes(Source);
+            var ms = new MemoryStream();
+            mobjCryptoService.Key = GetLegalKey();
+            mobjCryptoService.IV = GetLegalIV();
+            var encrypto = mobjCryptoService.CreateEncryptor();
+            var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
+            cs.Write(bytIn, 0, bytIn.Length);
+            cs.FlushFinalBlock();
+            ms.Close();
+            var bytOut = ms.ToArray();
+            return Convert.ToBase64String(bytOut);
+        }
+
+        /// <summary>
+        ///     解密方法
+        /// </summary>
+        /// <param name="Source">待解密的串</param>
+        /// <returns>经过解密的串</returns>
+        public static string Decrypto(this string Source)
+        {
+            var bytIn = Convert.FromBase64String(Source);
+            var ms = new MemoryStream(bytIn, 0, bytIn.Length);
+            mobjCryptoService.Key = GetLegalKey();
+            mobjCryptoService.IV = GetLegalIV();
+            var encrypto = mobjCryptoService.CreateDecryptor();
+            var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
+            var sr = new StreamReader(cs);
+            return sr.ReadToEnd();
+        }
+    }
+}

+ 60 - 0
Masuit.Tools/Security/HashEncode.cs

@@ -0,0 +1,60 @@
+using System;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Masuit.Tools.Security
+{
+    /// <summary>
+    /// 得到随机安全码(哈希加密)。
+    /// </summary>
+    public class HashEncode
+    {
+        /// <summary>
+        /// 哈希加密
+        /// </summary>
+        public HashEncode()
+        {
+            //
+            // TODO: 在此处添加构造函数逻辑
+            //
+        }
+        /// <summary>
+        /// 得到随机哈希加密字符串
+        /// </summary>
+        /// <returns></returns>
+        public static string GetSecurity()
+        {
+            string Security = HashEncoding(GetRandomValue());
+            return Security;
+        }
+        /// <summary>
+        /// 得到一个随机数值
+        /// </summary>
+        /// <returns></returns>
+        public static string GetRandomValue()
+        {
+            Random Seed = new Random();
+            string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
+            return RandomVaule;
+        }
+        /// <summary>
+        /// 哈希加密一个字符串
+        /// </summary>
+        /// <param name="Security"></param>
+        /// <returns></returns>
+        public static string HashEncoding(string Security)
+        {
+            byte[] Value;
+            UnicodeEncoding Code = new UnicodeEncoding();
+            byte[] Message = Code.GetBytes(Security);
+            SHA512Managed Arithmetic = new SHA512Managed();
+            Value = Arithmetic.ComputeHash(Message);
+            Security = "";
+            foreach (byte o in Value)
+            {
+                Security += (int)o + "O";
+            }
+            return Security;
+        }
+    }
+}

+ 393 - 0
Masuit.Tools/Security/RSACryption.cs

@@ -0,0 +1,393 @@
+using System;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Masuit.Tools.Security
+{
+    /// <summary> 
+    /// RSA加密解密及RSA签名和验证
+    /// </summary> 
+    public class RSACryption
+    {
+        /// <summary>
+        /// RSA加密
+        /// </summary>
+        public RSACryption()
+        {
+        }
+
+        #region RSA 加密解密 
+
+        #region RSA 的密钥产生 
+
+        /// <summary>
+        /// RSA 的密钥产生 产生私钥 和公钥 
+        /// </summary>
+        /// <param name="xmlKeys"></param>
+        /// <param name="xmlPublicKey"></param>
+        public void RSAKey(out string xmlKeys, out string xmlPublicKey)
+        {
+            System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
+            xmlKeys = rsa.ToXmlString(true);
+            xmlPublicKey = rsa.ToXmlString(false);
+        }
+        #endregion
+
+        #region RSA的加密函数 
+        //############################################################################## 
+        //RSA 方式加密 
+        //说明KEY必须是XML的行式,返回的是字符串 
+        //在有一点需要说明!!该加密方式有 长度 限制的!! 
+        //############################################################################## 
+
+        //RSA的加密函数  string
+        /// <summary>
+        /// RSA的加密函数 string
+        /// </summary>
+        /// <param name="xmlPublicKey">公钥</param>
+        /// <param name="mStrEncryptString">需要加密的字符串</param>
+        /// <returns>加密后的内容</returns>
+        public string RSAEncrypt(string mStrEncryptString, string xmlPublicKey)
+        {
+            byte[] PlainTextBArray;
+            byte[] CypherTextBArray;
+            string Result;
+            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
+            rsa.FromXmlString(xmlPublicKey);
+            PlainTextBArray = (new UnicodeEncoding()).GetBytes(mStrEncryptString);
+            CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
+            Result = Convert.ToBase64String(CypherTextBArray);
+            return Result;
+        }
+        //RSA的加密函数 byte[]
+        /// <summary>
+        /// RSA的加密函数 byte[]
+        /// </summary>
+        /// <param name="xmlPublicKey">公钥</param>
+        /// <param name="EncryptString">需要加密的字节数组</param>
+        /// <returns>加密后的内容</returns>
+        public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
+        {
+            byte[] CypherTextBArray;
+            string Result;
+            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
+            rsa.FromXmlString(xmlPublicKey);
+            CypherTextBArray = rsa.Encrypt(EncryptString, false);
+            Result = Convert.ToBase64String(CypherTextBArray);
+            return Result;
+        }
+        #endregion
+
+        #region RSA的解密函数 
+        //RSA的解密函数  string
+        /// <summary>
+        /// RSA的解密函数  string
+        /// </summary>
+        /// <param name="xmlPrivateKey">私钥</param>
+        /// <param name="m_strDecryptString">需要解密的字符串</param>
+        /// <returns>解密后的内容</returns>
+        public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
+        {
+            byte[] PlainTextBArray;
+            byte[] DypherTextBArray;
+            string Result;
+            System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
+            rsa.FromXmlString(xmlPrivateKey);
+            PlainTextBArray = Convert.FromBase64String(m_strDecryptString);
+            DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
+            Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
+            return Result;
+        }
+
+        //RSA的解密函数  byte
+        /// <summary>
+        /// RSA的解密函数  byte
+        /// </summary>
+        /// <param name="xmlPrivateKey">私钥</param>
+        /// <param name="DecryptString">需要解密的字符串</param>
+        /// <returns>解密后的内容</returns>
+        public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
+        {
+            byte[] DypherTextBArray;
+            string Result;
+            System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
+            rsa.FromXmlString(xmlPrivateKey);
+            DypherTextBArray = rsa.Decrypt(DecryptString, false);
+            Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
+            return Result;
+        }
+        #endregion
+
+        #endregion
+
+        #region RSA数字签名 
+
+        #region 获取Hash描述表 
+        //获取Hash描述表 
+        /// <summary>
+        /// 获取Hash描述表
+        /// </summary>
+        /// <param name="m_strSource">源数据</param>
+        /// <param name="HashData">哈希数据</param>
+        /// <returns></returns>
+        public bool GetHash(string m_strSource, ref byte[] HashData)
+        {
+            //从字符串中取得Hash描述 
+            byte[] Buffer;
+            System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
+            Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
+            HashData = MD5.ComputeHash(Buffer);
+
+            return true;
+        }
+
+        //获取Hash描述表 
+        /// <summary>
+        /// 获取Hash描述表
+        /// </summary>
+        /// <param name="m_strSource">源数据</param>
+        /// <param name="strHashData">哈希数据</param>
+        /// <returns></returns>
+        public bool GetHash(string m_strSource, ref string strHashData)
+        {
+            //从字符串中取得Hash描述 
+            byte[] Buffer;
+            byte[] HashData;
+            System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
+            Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
+            HashData = MD5.ComputeHash(Buffer);
+            strHashData = Convert.ToBase64String(HashData);
+            return true;
+        }
+
+        //获取Hash描述表 
+        /// <summary>
+        /// 从文件流获取Hash描述表
+        /// </summary>
+        /// <param name="objFile">源文件</param>
+        /// <param name="HashData">哈希字节数据</param>
+        /// <returns></returns>
+        public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
+        {
+            //从文件中取得Hash描述 
+            System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
+            HashData = MD5.ComputeHash(objFile);
+            objFile.Close();
+            return true;
+        }
+
+        //获取Hash描述表 
+        /// <summary>
+        /// 从文件流获取Hash描述表
+        /// </summary>
+        /// <param name="objFile">源文件</param>
+        /// <param name="strHashData">哈希数据</param>
+        /// <returns></returns>
+        public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
+        {
+            //从文件中取得Hash描述 
+            byte[] HashData;
+            System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
+            HashData = MD5.ComputeHash(objFile);
+            objFile.Close();
+            strHashData = Convert.ToBase64String(HashData);
+            return true;
+        }
+        #endregion
+
+        #region RSA签名 
+        //RSA签名 
+        /// <summary>
+        /// RSA签名
+        /// </summary>
+        /// <param name="p_strKeyPrivate">私钥</param>
+        /// <param name="HashbyteSignature">签名字节数据</param>
+        /// <param name="EncryptedSignatureData">加密字节数据</param>
+        /// <returns></returns>
+        public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
+        {
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPrivate);
+            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
+            //设置签名的算法为MD5 
+            RSAFormatter.SetHashAlgorithm("MD5");
+            //执行签名 
+            EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
+            return true;
+        }
+
+        //RSA签名 
+        /// <summary>
+        /// RSA签名
+        /// </summary>
+        /// <param name="p_strKeyPrivate">私钥</param>
+        /// <param name="HashbyteSignature">签名字节数据</param>
+        /// <param name="m_strEncryptedSignatureData">加密字符串数据</param>
+        /// <returns></returns>
+        public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
+        {
+            byte[] EncryptedSignatureData;
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPrivate);
+            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
+            //设置签名的算法为MD5 
+            RSAFormatter.SetHashAlgorithm("MD5");
+            //执行签名 
+            EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
+            m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
+            return true;
+        }
+
+        //RSA签名 
+        /// <summary>
+        /// RSA签名
+        /// </summary>
+        /// <param name="p_strKeyPrivate">私钥</param>
+        /// <param name="m_strHashbyteSignature">签名字符串数据</param>
+        /// <param name="EncryptedSignatureData">加密字节数据</param>
+        /// <returns></returns>
+        public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
+        {
+            byte[] HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPrivate);
+            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
+            //设置签名的算法为MD5 
+            RSAFormatter.SetHashAlgorithm("MD5");
+            //执行签名 
+            EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
+            return true;
+        }
+
+        //RSA签名 
+        /// <summary>
+        /// RSA签名
+        /// </summary>
+        /// <param name="p_strKeyPrivate">私钥</param>
+        /// <param name="m_strHashbyteSignature">签名字符串数据</param>
+        /// <param name="m_strEncryptedSignatureData">加密字符串数据</param>
+        /// <returns></returns>
+        public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
+        {
+            byte[] HashbyteSignature;
+            byte[] EncryptedSignatureData;
+            HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPrivate);
+            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
+            //设置签名的算法为MD5 
+            RSAFormatter.SetHashAlgorithm("MD5");
+            //执行签名 
+            EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
+            m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
+            return true;
+        }
+        #endregion
+
+        #region RSA 签名验证 
+
+        /// <summary>
+        /// RSA 签名验证 
+        /// </summary>
+        /// <param name="p_strKeyPublic">公钥</param>
+        /// <param name="HashbyteDeformatter">哈希字节数据</param>
+        /// <param name="DeformatterData">格式字节数据</param>
+        /// <returns></returns>
+        public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
+        {
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPublic);
+            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
+            //指定解密的时候HASH算法为MD5 
+            RSADeformatter.SetHashAlgorithm("MD5");
+            if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// RSA 签名验证 
+        /// </summary>
+        /// <param name="p_strKeyPublic">公钥</param>
+        /// <param name="p_strHashbyteDeformatter">哈希字符串数据</param>
+        /// <param name="DeformatterData">格式字节数据</param>
+        /// <returns></returns>
+        public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
+        {
+            byte[] HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPublic);
+            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
+            //指定解密的时候HASH算法为MD5 
+            RSADeformatter.SetHashAlgorithm("MD5");
+            if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// RSA 签名验证
+        /// </summary>
+        /// <param name="p_strKeyPublic">公钥</param>
+        /// <param name="HashbyteDeformatter">哈希字节数据</param>
+        /// <param name="p_strDeformatterData">格式字符串数据</param>
+        /// <returns></returns>
+        public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
+        {
+            byte[] DeformatterData;
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPublic);
+            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
+            //指定解密的时候HASH算法为MD5 
+            RSADeformatter.SetHashAlgorithm("MD5");
+            DeformatterData = Convert.FromBase64String(p_strDeformatterData);
+            if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// RSA 签名验证
+        /// </summary>
+        /// <param name="p_strKeyPublic">公钥</param>
+        /// <param name="p_strHashbyteDeformatter">哈希字符串数据</param>
+        /// <param name="p_strDeformatterData">格式字符串数据</param>
+        /// <returns></returns>
+        public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
+        {
+            byte[] DeformatterData;
+            byte[] HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
+            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
+            RSA.FromXmlString(p_strKeyPublic);
+            System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
+            //指定解密的时候HASH算法为MD5 
+            RSADeformatter.SetHashAlgorithm("MD5");
+            DeformatterData = Convert.FromBase64String(p_strDeformatterData);
+            if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
+            {
+                return true;
+            }
+            else
+            {
+                return false;
+            }
+        }
+        #endregion
+        #endregion
+    }
+}

+ 334 - 0
Masuit.Tools/Strings/ConvertJson.cs

@@ -0,0 +1,334 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Data;
+using System.Data.Common;
+using System.Reflection;
+using System.Text;
+
+namespace Masuit.Tools.Strings
+{
+    /// <summary>
+    /// JSON转换类
+    /// </summary>
+    public static class ConvertJson
+    {
+        #region 私有方法
+        /// <summary>
+        /// 过滤特殊字符
+        /// </summary>
+        /// <param name="s">源数据</param>
+        private static string String2Json(String s)
+        {
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < s.Length; i++)
+            {
+                char c = s[i];
+                switch (c)
+                {
+                    case '\"':
+                        sb.Append("\\\""); break;
+                    case '\\':
+                        sb.Append("\\\\"); break;
+                    case '/':
+                        sb.Append("\\/"); break;
+                    case '\b':
+                        sb.Append("\\b"); break;
+                    case '\f':
+                        sb.Append("\\f"); break;
+                    case '\n':
+                        sb.Append("\\n"); break;
+                    case '\r':
+                        sb.Append("\\r"); break;
+                    case '\t':
+                        sb.Append("\\t"); break;
+                    default:
+                        sb.Append(c); break;
+                }
+            }
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 格式化字符型、日期型、布尔型
+        /// </summary>
+        /// <param name="str">源数据</param>
+        /// <param name="type">类型</param>
+        private static string StringFormat(string str, Type type)
+        {
+            if (type == typeof(string))
+            {
+                str = String2Json(str);
+                str = "\"" + str + "\"";
+            }
+            else if (type == typeof(DateTime))
+            {
+                str = "\"" + str + "\"";
+            }
+            else if (type == typeof(bool))
+            {
+                str = str.ToLower();
+            }
+            else if (type != typeof(string) && string.IsNullOrEmpty(str))
+            {
+                str = "\"" + str + "\"";
+            }
+            return str;
+        }
+        #endregion
+
+        #region List转换成Json
+        /// <summary>
+        /// List转换成Json
+        /// </summary>
+        /// <typeparam name="T">泛型T</typeparam>
+        /// <param name="list">集合数据</param>
+        public static string ListToJson<T>(IList<T> list)
+        {
+            object obj = list[0];
+            return ListToJson<T>(list, obj.GetType().Name);
+        }
+
+        /// <summary>
+        /// List转换成Json 
+        /// </summary>
+        /// <typeparam name="T">泛型T</typeparam>
+        /// <param name="list">集合数据</param>
+        /// <param name="jsonName">json名</param>
+        public static string ListToJson<T>(IList<T> list, string jsonName)
+        {
+            StringBuilder Json = new StringBuilder();
+            if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
+            Json.Append("{\"" + jsonName + "\":[");
+            if (list.Count > 0)
+            {
+                for (int i = 0; i < list.Count; i++)
+                {
+                    T obj = Activator.CreateInstance<T>();
+                    PropertyInfo[] pi = obj.GetType().GetProperties();
+                    Json.Append("{");
+                    for (int j = 0; j < pi.Length; j++)
+                    {
+                        Type type = pi[j].GetValue(list[i], null).GetType();
+                        Json.Append("\"" + pi[j].Name + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
+
+                        if (j < pi.Length - 1)
+                        {
+                            Json.Append(",");
+                        }
+                    }
+                    Json.Append("}");
+                    if (i < list.Count - 1)
+                    {
+                        Json.Append(",");
+                    }
+                }
+            }
+            Json.Append("]}");
+            return Json.ToString();
+        }
+        #endregion
+
+        #region 对象转换为Json
+        /// <summary> 
+        /// 对象转换为Json 
+        /// </summary> 
+        /// <param name="jsonObject">对象</param> 
+        /// <returns>Json字符串</returns> 
+        public static string ToJson(object jsonObject)
+        {
+            string jsonString = "{";
+            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
+            for (int i = 0; i < propertyInfo.Length; i++)
+            {
+                object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
+                string value = string.Empty;
+                if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
+                {
+                    value = "'" + objectValue.ToString() + "'";
+                }
+                else if (objectValue is string)
+                {
+                    value = "'" + ToJson(objectValue.ToString()) + "'";
+                }
+                else if (objectValue is IEnumerable)
+                {
+                    value = ToJson((IEnumerable)objectValue);
+                }
+                else
+                {
+                    value = ToJson(objectValue.ToString());
+                }
+                jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
+            }
+            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
+            return jsonString + "}";
+        }
+        #endregion
+
+        #region 对象集合转换Json
+        /// <summary> 
+        /// 对象集合转换Json 
+        /// </summary> 
+        /// <param name="array">集合对象</param> 
+        /// <returns>Json字符串</returns> 
+        public static string ToJson(IEnumerable array)
+        {
+            string jsonString = "[";
+            foreach (object item in array)
+            {
+                jsonString += ToJson(item) + ",";
+            }
+            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
+            return jsonString + "]";
+        }
+        #endregion
+
+        #region 普通集合转换Json
+        /// <summary> 
+        /// 普通集合转换Json 
+        /// </summary> 
+        /// <param name="array">集合对象</param> 
+        /// <returns>Json字符串</returns> 
+        public static string ToArrayString(IEnumerable array)
+        {
+            string jsonString = "[";
+            foreach (object item in array)
+            {
+                jsonString = ToJson(item.ToString()) + ",";
+            }
+            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
+            return jsonString + "]";
+        }
+        #endregion
+
+        #region  DataSet转换为Json
+        /// <summary> 
+        /// DataSet转换为Json 
+        /// </summary> 
+        /// <param name="dataSet">DataSet对象</param> 
+        /// <returns>Json字符串</returns> 
+        public static string ToJson(DataSet dataSet)
+        {
+            string jsonString = "{";
+            foreach (DataTable table in dataSet.Tables)
+            {
+                jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
+            }
+            jsonString = jsonString.TrimEnd(',');
+            return jsonString + "}";
+        }
+        #endregion
+
+        #region Datatable转换为Json
+        /// <summary> 
+        /// Datatable转换为Json 
+        /// </summary> 
+        /// <param name="dt">Datatable对象</param> 
+        /// <returns>Json字符串</returns> 
+        public static string ToJson(DataTable dt)
+        {
+            StringBuilder jsonString = new StringBuilder();
+            jsonString.Append("[");
+            DataRowCollection drc = dt.Rows;
+            for (int i = 0; i < drc.Count; i++)
+            {
+                jsonString.Append("{");
+                for (int j = 0; j < dt.Columns.Count; j++)
+                {
+                    string strKey = dt.Columns[j].ColumnName;
+                    string strValue = drc[i][j].ToString();
+                    Type type = dt.Columns[j].DataType;
+                    jsonString.Append("\"" + strKey + "\":");
+                    strValue = StringFormat(strValue, type);
+                    if (j < dt.Columns.Count - 1)
+                    {
+                        jsonString.Append(strValue + ",");
+                    }
+                    else
+                    {
+                        jsonString.Append(strValue);
+                    }
+                }
+                jsonString.Append("},");
+            }
+            jsonString.Remove(jsonString.Length - 1, 1);
+            jsonString.Append("]");
+            return jsonString.ToString();
+        }
+
+        /// <summary>
+        /// DataTable转换为Json 
+        /// </summary>
+        /// <param name="dt">内存表</param>
+        /// <param name="jsonName">json名</param>
+        public static string ToJson(DataTable dt, string jsonName)
+        {
+            StringBuilder Json = new StringBuilder();
+            if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
+            Json.Append("{\"" + jsonName + "\":[");
+            if (dt.Rows.Count > 0)
+            {
+                for (int i = 0; i < dt.Rows.Count; i++)
+                {
+                    Json.Append("{");
+                    for (int j = 0; j < dt.Columns.Count; j++)
+                    {
+                        Type type = dt.Rows[i][j].GetType();
+                        Json.Append("\"" + dt.Columns[j].ColumnName + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
+                        if (j < dt.Columns.Count - 1)
+                        {
+                            Json.Append(",");
+                        }
+                    }
+                    Json.Append("}");
+                    if (i < dt.Rows.Count - 1)
+                    {
+                        Json.Append(",");
+                    }
+                }
+            }
+            Json.Append("]}");
+            return Json.ToString();
+        }
+        #endregion
+
+        #region DataReader转换为Json
+        /// <summary> 
+        /// DataReader转换为Json 
+        /// </summary> 
+        /// <param name="dataReader">DataReader对象</param> 
+        /// <returns>Json字符串</returns> 
+        public static string ToJson(DbDataReader dataReader)
+        {
+            StringBuilder jsonString = new StringBuilder();
+            jsonString.Append("[");
+            while (dataReader.Read())
+            {
+                jsonString.Append("{");
+                for (int i = 0; i < dataReader.FieldCount; i++)
+                {
+                    Type type = dataReader.GetFieldType(i);
+                    string strKey = dataReader.GetName(i);
+                    string strValue = dataReader[i].ToString();
+                    jsonString.Append("\"" + strKey + "\":");
+                    strValue = StringFormat(strValue, type);
+                    if (i < dataReader.FieldCount - 1)
+                    {
+                        jsonString.Append(strValue + ",");
+                    }
+                    else
+                    {
+                        jsonString.Append(strValue);
+                    }
+                }
+                jsonString.Append("},");
+            }
+            dataReader.Close();
+            jsonString.Remove(jsonString.Length - 1, 1);
+            jsonString.Append("]");
+            return jsonString.ToString();
+        }
+        #endregion
+    }
+}

+ 187 - 0
Masuit.Tools/Strings/JsonHelper.cs

@@ -0,0 +1,187 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+
+namespace Masuit.Tools.Strings
+{
+    /// <summary>
+    /// Json帮助类
+    /// </summary>
+    public static class JsonHelper
+    {
+        /// <summary>
+        /// 将对象转换成json数据
+        /// </summary>
+        /// <param name="obj">实例对象</param>
+        /// <returns>json</returns>
+        public static string GetJsonFromObject(this object obj)
+        {
+            string str;
+            StringBuilder builder = new StringBuilder();
+            builder.Append("{");
+            Type type = obj.GetType();
+            PropertyInfo property = type.GetProperty("Values");
+            PropertyInfo info2 = type.GetProperty("Keys");
+            if ((property != null) || (info2 != null))
+            {
+                ICollection is2 = (ICollection)property.GetValue(obj, null);
+                ICollection is3 = (ICollection)info2.GetValue(obj, null);
+                str = string.Empty;
+                List<string> list = new List<string>();
+                foreach (object obj2 in is3)
+                {
+                    list.Add(obj2.ToString());
+                }
+                int num = 0;
+                str = string.Empty;
+                foreach (object obj2 in is2)
+                {
+                    Type type2 = obj2.GetType();
+                    if (((type2.ToString() == "System.String") || (type2.ToString() == "System.Int32")) || (type2.ToString() == "System.Boolean"))
+                    {
+                        if (obj2 is string)
+                        {
+                            str = str + ",\"" + list[num] + "\":\"" + obj2.ToString().Replace(@"\", @"\\").Replace("\"", "\\\"").Replace("\n", @"\n").Replace("\r", @"\r") + "\"";
+                        }
+                        else
+                        {
+                            str = str + ",\"" + list[num] + "\":" + obj2.ToString();
+                        }
+                    }
+                    else
+                    {
+                        str = str + ",\"" + list[num] + "\":{" + tojson(obj2) + "}";
+                    }
+                    num++;
+                }
+                if (str.Length > 0)
+                {
+                    str = str.Substring(1);
+                    builder.Append(str);
+                }
+            }
+            else
+            {
+                str = string.Empty;
+                if ((obj is int) || (obj is bool))
+                {
+                    str = str + ",\"" + type.Name + "\":" + obj.ToString();
+                }
+                else if (obj is string)
+                {
+                    str = str + ",\"" + type.Name + "\":\"" + obj.ToString().Replace(@"\", @"\\").Replace("\"", "\\\"").Replace("\n", @"\n").Replace("\r", @"\r") + "\"";
+                }
+                else
+                {
+                    foreach (PropertyInfo info3 in type.GetProperties())
+                    {
+                        object obj3 = info3.GetValue(obj, null);
+                        Type type3 = obj3.GetType();
+                        if ((obj3 is int) || (obj3 is bool))
+                        {
+                            str = str + ",\"" + info3.Name + "\":" + obj3.ToString();
+                        }
+                        else if (obj3 is string)
+                        {
+                            str = str + ",\"" + info3.Name + "\":\"" + obj3.ToString().Replace(@"\", @"\\").Replace("\"", "\\\"").Replace("\n", @"\n").Replace("\r", @"\r") + "\"";
+                        }
+                        else
+                        {
+                            str = str + ",\"" + info3.Name + "\":{" + tojson(obj3) + "}";
+                        }
+                    }
+                }
+                if (str.Length > 0)
+                {
+                    builder.Append(str.Substring(1));
+                }
+            }
+            builder.Append("}");
+            return builder.ToString();
+        }
+
+        private static string tojson(object obj)
+        {
+            string str;
+            Type type = obj.GetType();
+            string str2 = string.Empty;
+            PropertyInfo property = type.GetProperty("Values");
+            PropertyInfo info2 = type.GetProperty("Keys");
+            if ((property != null) && (info2 != null))
+            {
+                ICollection is2 = (ICollection)info2.GetValue(obj, null);
+                ICollection is3 = (ICollection)property.GetValue(obj, null);
+                str = string.Empty;
+                List<string> list = new List<string>();
+                foreach (object obj2 in is2)
+                {
+                    list.Add(obj2.ToString());
+                }
+                int num = 0;
+                str = string.Empty;
+                foreach (object obj2 in is3)
+                {
+                    Type type2 = obj2.GetType();
+                    if (((type2.ToString() == "System.String") || (type2.ToString() == "System.Int32")) || (type2.ToString() == "System.Boolean"))
+                    {
+                        if (obj2 is string)
+                        {
+                            str = str + ",\"" + list[num] + "\":\"" + obj2.ToString().Replace(@"\", @"\\").Replace("\"", "\\\"").Replace("\n", @"\n").Replace("\r", @"\r") + "\"";
+                        }
+                        else
+                        {
+                            str = str + ",\"" + list[num] + "\":" + obj2.ToString();
+                        }
+                    }
+                    else
+                    {
+                        str = str + ",\"" + list[num] + "\":{" + tojson(obj2) + "}";
+                    }
+                    num++;
+                }
+                if (str.Length > 0)
+                {
+                    str = str.Substring(1);
+                    str2 += str;
+                }
+                return str2;
+            }
+            str = string.Empty;
+            if ((obj is int) || (obj is bool))
+            {
+                str = str + ",\"" + type.Name + "\":" + obj.ToString();
+            }
+            else if (obj is string)
+            {
+                str = str + ",\"" + type.Name + "\":\"" + obj.ToString().Replace(@"\", @"\\").Replace("\"", "\\\"").Replace("\n", @"\n").Replace("\r", @"\r") + "\"";
+            }
+            else
+            {
+                foreach (PropertyInfo info3 in type.GetProperties())
+                {
+                    object obj3 = info3.GetValue(obj, null);
+                    Type type3 = obj3.GetType();
+                    if ((obj3 is int) || (obj3 is bool))
+                    {
+                        str = str + ",\"" + info3.Name + "\":" + obj3.ToString();
+                    }
+                    else if (obj3 is string)
+                    {
+                        str = str + ",\"" + info3.Name + "\":\"" + obj3.ToString().Replace(@"\", @"\\").Replace("\"", "\\\"").Replace("\n", @"\n").Replace("\r", @"\r") + "\"";
+                    }
+                    else
+                    {
+                        str = str + ",\"" + info3.Name + "\":{" + tojson(obj3) + "}";
+                    }
+                }
+            }
+            if (str.Length > 0)
+            {
+                str2 += str.Substring(1);
+            }
+            return str2;
+        }
+    }
+}

+ 676 - 0
Masuit.Tools/Strings/StringExt.cs

@@ -0,0 +1,676 @@
+using System;
+using System.Text.RegularExpressions;
+
+namespace Masuit.Tools.Strings
+{
+    /// <summary>
+    /// 字符串扩展类
+    /// </summary>
+    public static class StringExt
+    {
+        #region UBB转HTML
+
+        /// <summary>
+        /// UBB代码处理函数
+        /// </summary>
+        /// <param name="ubbStr">输入字符串</param>
+        /// <returns>输出字符串</returns>
+        public static string UbbToHtml(this string ubbStr)
+        {
+            Regex r;
+            Match m;
+
+            #region 处理空格
+
+            ubbStr = ubbStr.Replace(" ", "&nbsp;");
+
+            #endregion
+
+            #region 处理&符
+
+            ubbStr = ubbStr.Replace("&", "&amp;");
+
+            #endregion
+
+            #region 处理单引号
+
+            ubbStr = ubbStr.Replace("'", "’");
+
+            #endregion
+
+            #region 处理双引号
+
+            ubbStr = ubbStr.Replace("\"", "&quot;");
+
+            #endregion
+
+            #region html标记符
+
+            ubbStr = ubbStr.Replace("<", "&lt;");
+            ubbStr = ubbStr.Replace(">", "&gt;");
+
+            #endregion
+
+            #region 处理换行
+
+            //处理换行,在每个新行的前面添加两个全角空格
+            r = new Regex(@"(\r\n((&nbsp;)| )+)(?<正文>\S+)", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<BR>  " + m.Groups["正文"]);
+            //处理换行,在每个新行的前面添加两个全角空格
+            ubbStr = ubbStr.Replace("\r\n", "<BR>");
+
+            #endregion
+
+            #region 处[b][/b]标记
+
+            r = new Regex(@"(\[b\])([ \S\t]*?)(\[\/b\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<B>" + m.Groups[2] + "</B>");
+
+            #endregion
+
+            #region 处[i][/i]标记
+
+            r = new Regex(@"(\[i\])([ \S\t]*?)(\[\/i\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<I>" + m.Groups[2] + "</I>");
+
+            #endregion
+
+            #region 处[u][/u]标记
+
+            r = new Regex(@"(\[U\])([ \S\t]*?)(\[\/U\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<U>" + m.Groups[2] + "</U>");
+
+            #endregion
+
+            #region 处[p][/p]标记
+
+            //处[p][/p]标记
+            r = new Regex(@"((\r\n)*\[p\])(.*?)((\r\n)*\[\/p\])", RegexOptions.IgnoreCase | RegexOptions.Singleline);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<P class=\"pstyle\">" + m.Groups[3] + "</P>");
+
+            #endregion
+
+            #region 处[sup][/sup]标记
+
+            //处[sup][/sup]标记
+            r = new Regex(@"(\[sup\])([ \S\t]*?)(\[\/sup\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<SUP>" + m.Groups[2] + "</SUP>");
+
+            #endregion
+
+            #region 处[sub][/sub]标记
+
+            //处[sub][/sub]标记
+            r = new Regex(@"(\[sub\])([ \S\t]*?)(\[\/sub\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<SUB>" + m.Groups[2] + "</SUB>");
+
+            #endregion
+
+            #region 处标记
+
+            //处标记
+            r = new Regex(@"(\[url\])([ \S\t]*?)(\[\/url\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<A href=\"" + m.Groups[2] + "\" target=\"_blank\">" + m.Groups[2] + "</A>");
+            }
+
+            #endregion
+
+            #region 处[url=xxx][/url]标记
+
+            //处[url=xxx][/url]标记
+            r = new Regex(@"(\[url=([ \S\t]+)\])([ \S\t]*?)(\[\/url\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<A href=\"" + m.Groups[2] + "\" target=\"_blank\">"
+                   + m.Groups[3] + "</A>");
+            }
+
+            #endregion
+
+            #region 处[email][/email]标记
+
+            //处[email][/email]标记
+            r = new Regex(@"(\[email\])([ \S\t]*?)(\[\/email\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<A href=\"mailto:" + m.Groups[2] + "\" target=\"_blank\">" +
+                   m.Groups[2] + "</A>");
+            }
+
+            #endregion
+
+            #region 处[email=xxx][/email]标记
+
+            //处[email=xxx][/email]标记
+            r = new Regex(@"(\[email=([ \S\t]+)\])([ \S\t]*?)(\[\/email\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<A href=\"mailto:" + m.Groups[2] + "\" target=\"_blank\">" +
+                   m.Groups[3] + "</A>");
+            }
+
+            #endregion
+
+            #region 处[size=x][/size]标记
+
+            //处[size=x][/size]标记
+            r = new Regex(@"(\[size=([1-7])\])([ \S\t]*?)(\[\/size\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<FONT SIZE=" + m.Groups[2] + ">" +
+                   m.Groups[3] + "</FONT>");
+            }
+
+            #endregion
+
+            #region 处[color=x][/color]标记
+
+            //处[color=x][/color]标记
+            r = new Regex(@"(\[color=([\S]+)\])([ \S\t]*?)(\[\/color\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<FONT COLOR=" + m.Groups[2] + ">" +
+                   m.Groups[3] + "</FONT>");
+            }
+
+            #endregion
+
+            #region 处[font=x][/font]标记
+
+            //处[font=x][/font]标记
+            r = new Regex(@"(\[font=([\S]+)\])([ \S\t]*?)(\[\/font\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<FONT FACE=" + m.Groups[2] + ">" +
+                   m.Groups[3] + "</FONT>");
+            }
+
+            #endregion
+
+            #region 处理图片链接
+
+            //处理图片链接
+            r = new Regex("\\[picture\\](\\d+?)\\[\\/picture\\]", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<A href=\"ShowImage.aspx?Type=ALL&Action=forumImage&ImageID=" + m.Groups[1] + "\" target=\"_blank\"><IMG border=0 Title=\"点击打开新窗口查看\" src=\"ShowImage.aspx?Action=forumImage&ImageID=" + m.Groups[1] + "\"></A>");
+            }
+
+            #endregion
+
+            #region 处理[align=x][/align]
+
+            //处理[align=x][/align]
+            r = new Regex(@"(\[align=([\S]+)\])([ \S\t]*?)(\[\/align\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<P align=" + m.Groups[2] + ">" +
+                   m.Groups[3] + "</P>");
+            }
+
+            #endregion
+
+            #region 处[H=x][/H]标记
+
+            //处[H=x][/H]标记
+            r = new Regex(@"(\[H=([1-6])\])([ \S\t]*?)(\[\/H\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<H" + m.Groups[2] + ">" +
+                   m.Groups[3] + "</H" + m.Groups[2] + ">");
+            }
+
+            #endregion
+
+            #region 处理[list=x][*][/list]
+
+            //处理[list=x][*][/list]
+            r = new Regex(@"(\[list(=(A|a|I|i| ))?\]([ \S\t]*)\r\n)((\[\*\]([ \S\t]*\r\n))*?)(\[\/list\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                string strLI = m.Groups[5].ToString();
+                Regex rLI = new Regex(@"\[\*\]([ \S\t]*\r\n?)", RegexOptions.IgnoreCase);
+                Match mLI;
+                for (mLI = rLI.Match(strLI); mLI.Success; mLI = mLI.NextMatch())
+                    strLI = strLI.Replace(mLI.Groups[0].ToString(), "<LI>" + mLI.Groups[1]);
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                    "<UL TYPE=\"" + m.Groups[3] + "\"><B>" + m.Groups[4] + "</B>" +
+                    strLI + "</UL>");
+            }
+
+            #endregion
+
+            #region 处[SHADOW=x][/SHADOW]标记
+
+            //处[SHADOW=x][/SHADOW]标记
+            r = new Regex(@"(\[SHADOW=)(\d*?),(#*\w*?),(\d*?)\]([\S\t]*?)(\[\/SHADOW\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<TABLE WIDTH=" + m.Groups[2] + "STYLE=FILTER:SHADOW(COLOR=" + m.Groups[3] + ",STRENGTH=" + m.Groups[4] + ")>" + m.Groups[5] + "</TABLE>");
+            }
+
+            #endregion
+
+            #region 处[glow=x][/glow]标记
+
+            //处[glow=x][/glow]标记
+            r = new Regex(@"(\[glow=)(\d*?),(#*\w*?),(\d*?)\]([\S\t]*?)(\[\/glow\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<TABLE WIDTH=" + m.Groups[2] + "  STYLE=FILTER:GLOW(COLOR=" + m.Groups[3] + ", STRENGTH=" + m.Groups[4] + ")>" +
+                   m.Groups[5] + "</TABLE>");
+            }
+
+            #endregion
+
+            #region 处[center][/center]标记
+
+            r = new Regex(@"(\[center\])([ \S\t]*?)(\[\/center\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<CENTER>" + m.Groups[2] + "</CENTER>");
+
+            #endregion
+
+            #region 处[ IMG][ /IMG]标记
+
+            r = new Regex(@"(\[IMG\])(http|https|ftp):\/\/([ \S\t]*?)(\[\/IMG\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<br><a onfocus=this.blur() href=" + m.Groups[2] + "://" + m.Groups[3] + " target=_blank><IMG SRC=" + m.Groups[2] + "://" + m.Groups[3] + " border=0 alt=按此在新窗口浏览图片 onload=javascript:if(screen.width-333<this.width)this.width=screen.width-333></a>");
+
+            #endregion
+
+            #region 处[em]标记
+
+            r = new Regex(@"(\[em([\S\t]*?)\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<img src=pic/em" + m.Groups[2] + ".gif border=0 align=middle>");
+
+            #endregion
+
+            #region 处[flash=x][/flash]标记
+
+            //处[mp=x][/mp]标记
+            r = new Regex(@"(\[flash=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/flash\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<a href=" + m.Groups[4] + " TARGET=_blank><IMG SRC=pic/swf.gif border=0 alt=点击开新窗口欣赏该FLASH动画!> [全屏欣赏]</a><br><br><OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 width=" + m.Groups[2] + " height=" + m.Groups[3] + "><PARAM NAME=movie VALUE=" + m.Groups[4] + "><PARAM NAME=quality VALUE=high><param name=menu value=false><embed src=" + m.Groups[4] + " quality=high menu=false pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash width=" + m.Groups[2] + " height=" + m.Groups[3] + ">" + m.Groups[4] + "</embed></OBJECT>");
+            }
+
+            #endregion
+
+            #region 处[dir=x][/dir]标记
+
+            //处[dir=x][/dir]标记
+            r = new Regex(@"(\[dir=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/dir\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<object classid=clsid:166B1BCA-3F9C-11CF-8075-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0 width=" + m.Groups[2] + " height=" + m.Groups[3] + "><param name=src value=" + m.Groups[4] + "><embed src=" + m.Groups[4] + " pluginspage=http://www.macromedia.com/shockwave/download/ width=" + m.Groups[2] + " height=" + m.Groups[3] + "></embed></object>");
+            }
+
+            #endregion
+
+            #region 处[rm=x][/rm]标记
+
+            //处[rm=x][/rm]标记
+            r = new Regex(@"(\[rm=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/rm\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<OBJECT classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA class=OBJECT id=RAOCX width=" + m.Groups[2] + " height=" + m.Groups[3] + "><PARAM NAME=SRC VALUE=" + m.Groups[4] + "><PARAM NAME=CONSOLE VALUE=Clip1><PARAM NAME=CONTROLS VALUE=imagewindow><PARAM NAME=AUTOSTART VALUE=true></OBJECT><br><OBJECT classid=CLSID:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA height=32 id=video2 width=" + m.Groups[2] + "><PARAM NAME=SRC VALUE=" + m.Groups[4] + "><PARAM NAME=AUTOSTART VALUE=-1><PARAM NAME=CONTROLS VALUE=controlpanel><PARAM NAME=CONSOLE VALUE=Clip1></OBJECT>");
+            }
+
+            #endregion
+
+            #region 处[mp=x][/mp]标记
+
+            //处[mp=x][/mp]标记
+            r = new Regex(@"(\[mp=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/mp\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<object align=middle classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 class=OBJECT id=MediaPlayer width=" + m.Groups[2] + " height=" + m.Groups[3] + " ><param name=ShowStatusBar value=-1><param name=Filename value=" + m.Groups[4] + "><embed type=application/x-oleobject codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 flename=mp src=" + m.Groups[4] + "  width=" + m.Groups[2] + " height=" + m.Groups[3] + "></embed></object>");
+            }
+
+            #endregion
+
+            #region 处[qt=x][/qt]标记
+
+            //处[qt=x][/qt]标记
+            r = new Regex(@"(\[qt=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/qt\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<embed src=" + m.Groups[4] + " width=" + m.Groups[2] + " height=" + m.Groups[3] + " autoplay=true loop=false controller=true playeveryframe=false cache=false scale=TOFIT bgcolor=#000000 kioskmode=false targetcache=false pluginspage=http://www.apple.com/quicktime/>");
+            }
+
+            #endregion
+
+            #region 处[QUOTE][/QUOTE]标记
+
+            r = new Regex(@"(\[QUOTE\])([ \S\t]*?)(\[\/QUOTE\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<div style='border:#CCCCCC 1px dashed; width:94%; color:#999999; padding:3px; background:#F8F8F8'>" + m.Groups[2] + "</div><br /> ");
+
+            #endregion
+
+            #region 处[move][/move]标记
+
+            r = new Regex(@"(\[move\])([ \S\t]*?)(\[\/move\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<MARQUEE scrollamount=3>" + m.Groups[2] + "</MARQUEE>");
+
+            #endregion
+
+            #region 处[FLY][/FLY]标记
+
+            r = new Regex(@"(\[FLY\])([ \S\t]*?)(\[\/FLY\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<MARQUEE width=80% behavior=alternate scrollamount=3>" + m.Groups[2] + "</MARQUEE>");
+
+            #endregion
+
+            #region 处[image][/image]标记
+
+            //处[image][/image]标记
+            r = new Regex(@"(\[image\])([ \S\t]*?)(\[\/image\])", RegexOptions.IgnoreCase);
+            for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
+            {
+                ubbStr = ubbStr.Replace(m.Groups[0].ToString(),
+                   "<img src=\"" + m.Groups[2] + "\" border=0 align=middle><br>");
+            }
+
+            #endregion
+
+            return ubbStr;
+        }
+
+        #endregion
+
+        #region UBB转HTML方式2
+
+        /// <summary>
+        /// UBB转HTML方式2
+        /// </summary>
+        /// <param name="ubbStr">UBB 代码</param>
+        /// <returns></returns>
+        public static string UbbToHtml2(this string ubbStr)
+        {
+            ubbStr = ubbStr.Replace("&", "&amp;");
+            ubbStr = ubbStr.Replace("<", "&lt;");
+            ubbStr = ubbStr.Replace(">", "&gt;");
+            ubbStr = ubbStr.Replace(" ", "&nbsp;"); //空格
+            ubbStr = ubbStr.Replace("\n", "<br>"); //回车
+            Regex my = new Regex(@"(\[IMG\])(.[^\[]*)(\[\/IMG\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a href=""$2"" target=_blank><IMG SRC=""$2"" border=0 alt=按此在新窗口浏览图片 onload=""javascript:if(this.width>screen.width-333)this.width=screen.width-333""></a>");
+
+            my = new Regex(@"\[DIR=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/DIR]", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<object classid=clsid:166B1BCA-3F9C-11CF-8075-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0 width=$1 height=$2><param name=src value=$3><embed src=$3 pluginspage=http://www.macromedia.com/shockwave/download/ width=$1 height=$2></embed></object>");
+
+            my = new Regex(@"\[QT=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/QT]", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<embed src=$3 width=$1 height=$2 autoplay=true loop=false controller=true playeveryframe=false cache=false scale=TOFIT bgcolor=#000000 kioskmode=false targetcache=false pluginspage=http://www.apple.com/quicktime/>");
+
+            my = new Regex(@"\[MP=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/MP]", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<object align=middle classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 class=OBJECT id=MediaPlayer width=$1 height=$2 ><param name=ShowStatusBar value=-1><param name=Filename value=$3><embed type=application/x-oleobject codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 flename=mp src=$3  width=$1 height=$2></embed></object>");
+
+            my = new Regex(@"\[RM=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/RM]", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<OBJECT classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA class=OBJECT id=RAOCX width=$1 height=$2><PARAM NAME=SRC VALUE=$3><PARAM NAME=CONSOLE VALUE=Clip1><PARAM NAME=CONTROLS VALUE=imagewindow><PARAM NAME=AUTOSTART VALUE=true></OBJECT><br><OBJECT classid=CLSID:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA height=32 id=video2 width=$1><PARAM NAME=SRC VALUE=$3><PARAM NAME=AUTOSTART VALUE=-1><PARAM NAME=CONTROLS VALUE=controlpanel><PARAM NAME=CONSOLE VALUE=Clip1></OBJECT>");
+
+            my = new Regex(@"(\[FLASH\])(.[^\[]*)(\[\/FLASH\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 width=500 height=400><PARAM NAME=movie VALUE=""$2""><PARAM NAME=quality VALUE=high><embed src=""$2"" quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width=500 height=400>$2</embed></OBJECT>");
+
+            my = new Regex(@"(\[ZIP\])(.[^\[]*)(\[\/ZIP\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<br><IMG SRC=pic/zip.gif border=0> <a href=""$2"">点击下载该文件</a>");
+
+            my = new Regex(@"(\[RAR\])(.[^\[]*)(\[\/RAR\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<br><IMG SRC=pic/rar.gif border=0> <a href=""$2"">点击下载该文件</a>");
+
+            my = new Regex(@"(\[UPLOAD=(.[^\[]*)\])(.[^\[]*)(\[\/UPLOAD\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<br><IMG SRC=""pic/$2.gif"" border=0>此主题相关图片如下:<br><A HREF=""$3"" TARGET=_blank><IMG SRC=""$3"" border=0 alt=按此在新窗口浏览图片 onload=""javascript:if(this.width>screen.width-333)this.width=screen.width-333""></A>");
+
+            my = new Regex(@"(\[URL\])(http:\/\/.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<A HREF=""$2"" TARGET=_blank>$2</A>");
+
+            my = new Regex(@"(\[URL\])(.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<A HREF=""http://$2"" TARGET=_blank>$2</A>");
+
+            my = new Regex(@"(\[URL=(http:\/\/.[^\[]*)\])(.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<A HREF=""$2"" TARGET=_blank>$3</A>");
+
+            my = new Regex(@"(\[URL=(.[^\[]*)\])(.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<A HREF=""http://$2"" TARGET=_blank>$3</A>");
+
+            my = new Regex(@"(\[EMAIL\])(\S+\@.[^\[]*)(\[\/EMAIL\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<A HREF=""mailto:$2"">$2</A>");
+
+            my = new Regex(@"(\[EMAIL=(\S+\@.[^\[]*)\])(.[^\[]*)(\[\/EMAIL\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<A HREF=""mailto:$2"" TARGET=_blank>$3</A>");
+
+            my = new Regex(@"^(HTTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"(HTTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"[^>=""](HTTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"^(FTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"(FTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"[^>=""](FTP://[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"^(RTSP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"(RTSP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"[^>=""](RTSP://[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"^(MMS://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+            my = new Regex(@"(MMS://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"[^>=""](MMS://[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
+
+            my = new Regex(@"(\[HTML\])(.[^\[]*)(\[\/HTML\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<table width='100%' border='0' cellspacing='0' cellpadding='6' bgcolor=''><td><b>以下内容为程序代码:</b><br>$2</td></table>");
+
+            my = new Regex(@"(\[CODE\])(.[^\[]*)(\[\/CODE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<table width='100%' border='0' cellspacing='0' cellpadding='6' bgcolor=''><td><b>以下内容为程序代码:</b><br>$2</td></table>");
+
+            my = new Regex(@"(\[COLOR=(.[^\[]*)\])(.[^\[]*)(\[\/COLOR\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<font COLOR=$2>$3</font>");
+
+            my = new Regex(@"(\[FACE=(.[^\[]*)\])(.[^\[]*)(\[\/FACE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<font FACE=$2>$3</font>");
+
+            my = new Regex(@"(\[ALIGN=(.[^\[]*)\])(.*)(\[\/ALIGN\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<div ALIGN=$2>$3</div>");
+
+            my = new Regex(@"(\[QUOTE\])(.*)(\[\/QUOTE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<table cellpadding=0 cellspacing=0 border=0 WIDTH=94% bgcolor=#000000 align=center><tr><td><table width=100% cellpadding=5 cellspacing=1 border=0><TR><TD BGCOLOR=''>$2</table></table><br>");
+
+            my = new Regex(@"(\[MOVE\])(.*)(\[\/MOVE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<MARQUEE scrollamount=3>$2</marquee>");
+
+            my = new Regex(@"\[GLOW=*([0-9]*),*(#*[a-z0-9]*),*([0-9]*)\](.[^\[]*)\[\/GLOW]", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<table width=$1 style=""filter:glow(color=$2, strength=$3)"">$4</table>");
+
+            my = new Regex(@"\[SHADOW=*([0-9]*),*(#*[a-z0-9]*),*([0-9]*)\](.[^\[]*)\[\/SHADOW]", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<table width=$1 style=""filter:shadow(color=$2, strength=$3)"">$4</table>");
+
+            my = new Regex(@"(\[I\])(.[^\[]*)(\[\/I\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<i>$2</i>");
+
+            my = new Regex(@"(\[B\])(.[^\[]*)(\[\/U\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<u>$2</u>");
+
+            my = new Regex(@"(\[B\])(.[^\[]*)(\[\/B\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<b>$2</b>");
+
+            my = new Regex(@"(\[FLY\])(.[^\[]*)(\[\/FLY\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<marquee onmouseover='this.stop();' onmouseout='this.start();'>$2</marquee>");
+
+            my = new Regex(@"(\[SIZE=1\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<font size=1>$2</font>");
+
+            my = new Regex(@"(\[SIZE=2\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<font size=2>$2</font>");
+
+            my = new Regex(@"(\[SIZE=3\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<font size=3>$2</font>");
+
+            my = new Regex(@"(\[SIZE=4\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<font size=4>$2</font>");
+
+            my = new Regex(@"(\[CENTER\])(.[^\[]*)(\[\/CENTER\])", RegexOptions.IgnoreCase);
+            ubbStr = my.Replace(ubbStr, @"<center>$2</center>");
+
+            return ubbStr;
+        }
+
+        #endregion
+
+        #region Html转UBB
+
+        /// <summary>
+        /// Html转UBB
+        /// </summary>
+        /// <param name="chr">HTML代码</param>
+        /// <returns></returns>
+        public static string HtmltoUBB(this string chr)
+        {
+            if (chr == null)
+                return "";
+            chr = chr.Replace("&lt", "<");
+            chr = chr.Replace("&gt", ">");
+            chr = chr.Replace("<br/>", " ");
+            chr = Regex.Replace(chr, @"<a href=$1 target=_blank>$2</a>", @"[url=(?<x>[^]]*)](?<y>[^]]*)[/url]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<a href=$1 target=_blank>$1</a>", @"[url](?<x>[^]]*)[/url]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<a href=$1>$2</a>", @"[email=(?<x>[^]]*)](?<y>[^]]*)[/email]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<a href=$1>$1</a>", @"[email](?<x>[^]]*)[/email]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 width=500 height=400><PARAM NAME=movie VALUE=""$1""><PARAM NAME=quality VALUE=high><embed src=""$1"" quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width=500 height=400>$1</embed></OBJECT>", @"[flash](?<x>[^]]*)[/flash]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<IMG SRC=""$1"" border=0>", @"[img](?<x>[^]]*)[/img]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<font color=$1>$2</font>", @"[color=(?<x>[^]]*)](?<y>[^]]*)[/color]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<font face=$1>$2</font>", @"[face=(?<x>[^]]*)](?<y>[^]]*)[/face]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<font size=1>$1</font>", @"[size=1](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<font size=2>$1</font>", @"[size=2](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<font size=3>$1</font>", @"[size=3](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<font size=4>$1</font>", @"[size=4](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<align=$1>$2</align>", @"[align=(?<x>[^]]*)](?<y>[^]]*)[/align]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<marquee width=90% behavior=alternate scrollamount=3>$1</marquee>", @"[fly](?<x>[^]]*)[/fly]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<marquee scrollamount=3>$1</marquee>", @"[move](?<x>[^]]*)[/move]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<table width=$1 style='filter:glow(color=$2, strength=$3)'>$4</table>", @"[glow=(?<x>[^]]*),(?<y>[^]]*),(?<z>[^]]*)](?<w>[^]]*)[/glow]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<table width=$1 style='filter:shadow(color=$2, strength=$3)'>$4</table>", @"[shadow=(?<x>[^]]*),(?<y>[^]]*),(?<z>[^]]*)](?<w>[^]]*)[/shadow]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<b>$1</b>", @"[b](?<x>[^]]*)[/b]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<i>$1</i>", @"[i](?<x>[^]]*)[/i]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<u>$1</u>", @"[u](?<x>[^]]*)[/u]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<pre id=code><font size=1 face='Verdana, Arial' id=code>$1</font id=code></pre id=code>", @"[code](?<x>[^]]*)[/code]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<ul>$1</ul>", @"[list](?<x>[^]]*)[/list]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<ol type=1>$1</ol id=1>", @"[list=1](?<x>[^]]*)[/list]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<ol type=a>$1</ol id=a>", @"[list=a](?<x>[^]]*)[/list]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<li>$1</li>", @"[*](?<x>[^]]*)[/*]", RegexOptions.IgnoreCase);
+            chr = Regex.Replace(chr, @"<center>—— 以下是引用 ——<table border='1' width='80%' cellpadding='10' cellspacing='0' ><tr><td>$1</td></tr></table></center>", @"[quote](?<x>.*)[/quote]", RegexOptions.IgnoreCase);
+            return chr;
+        }
+
+        #endregion
+
+        #region 字符串转int
+
+        /// <summary>
+        /// 字符串转int
+        /// </summary>
+        /// <param name="s"></param>
+        /// <returns></returns>
+        public static int ToInt32(this string s)
+        {
+            try
+            {
+                return Convert.ToInt32(s);
+            }
+            catch (Exception)
+            {
+                return 0;
+            }
+        }
+
+        #endregion
+
+        #region 字符串转double
+
+        /// <summary>
+        /// 字符串转double
+        /// </summary>
+        /// <param name="s"></param>
+        /// <returns></returns>
+        public static double ToDouble(this string s)
+        {
+            try
+            {
+                return Convert.ToDouble(s);
+            }
+            catch (Exception)
+            {
+                return 0;
+            }
+        }
+
+        #endregion
+
+        /// <summary>
+        /// 将double转换成int
+        /// </summary>
+        /// <param name="num">double类型</param>
+        /// <returns>int类型</returns>
+        public static int DoubleToInt32(this double num)
+        {
+            return (int)Math.Floor(num);
+        }
+
+        #region 匹配Email
+
+        /// <summary>
+        /// 匹配Email
+        /// </summary>
+        /// <param name="s"></param>
+        /// <returns></returns>
+        public static bool MatchEmail(this string s)
+        {
+            return Regex.IsMatch(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
+        }
+
+        #endregion
+    }
+}

+ 146 - 0
Masuit.Tools/Strings/ValidateCode.cs

@@ -0,0 +1,146 @@
+using System;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Web;
+
+namespace Masuit.Tools.Strings
+{
+    /// <summary>
+    /// 画验证码
+    /// </summary>
+    public static class ValidateCode
+    {
+        /// <summary>
+        /// 验证码的最大长度
+        /// </summary>
+        public static int MaxLength
+        {
+            get { return 10; }
+        }
+
+        /// <summary>
+        /// 验证码的最小长度
+        /// </summary>
+        public static int MinLength
+        {
+            get { return 1; }
+        }
+
+        /// <summary>
+        /// 生成验证码
+        /// </summary>
+        /// <param name="length">指定验证码的长度</param>
+        /// <returns></returns>
+        public static string CreateValidateCode(int length)
+        {
+            int[] randMembers = new int[length];
+            int[] validateNums = new int[length];
+            string validateNumberStr = "";
+            //生成起始序列值
+            int seekSeek = unchecked((int)DateTime.Now.Ticks);
+            Random seekRand = new Random(seekSeek);
+            int beginSeek = seekRand.Next(0, int.MaxValue - length * 10000);
+            int[] seeks = new int[length];
+            for (int i = 0; i < length; i++)
+            {
+                beginSeek += 10000;
+                seeks[i] = beginSeek;
+            }
+            //生成随机数字
+            for (int i = 0; i < length; i++)
+            {
+                Random rand = new Random(seeks[i]);
+                int pownum = 1 * (int)Math.Pow(10, length);
+                randMembers[i] = rand.Next(pownum, int.MaxValue);
+            }
+            //抽取随机数字
+            for (int i = 0; i < length; i++)
+            {
+                string numStr = randMembers[i].ToString();
+                int numLength = numStr.Length;
+                Random rand = new Random();
+                int numPosition = rand.Next(0, numLength - 1);
+                validateNums[i] = int.Parse(numStr.Substring(numPosition, 1));
+            }
+            //生成验证码
+            for (int i = 0; i < length; i++)
+                validateNumberStr += validateNums[i].ToString();
+            return validateNumberStr;
+        }
+
+        /// <summary>
+        /// 创建验证码的图片
+        /// </summary>
+        /// <param name="validateCode">验证码序列</param>
+        /// <param name="context">当前的HttpContext上下文对象</param>
+        public static void CreateValidateGraphic(this string validateCode, HttpContext context)
+        {
+            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 24.0), 36);
+            Graphics g = Graphics.FromImage(image);
+            try
+            {
+                //生成随机生成器
+                Random random = new Random();
+                //清空图片背景色
+                g.Clear(Color.White);
+                //画图片的干扰线
+                for (int i = 0; i < 75; i++)
+                {
+                    int x1 = random.Next(image.Width);
+                    int x2 = random.Next(image.Width);
+                    int y1 = random.Next(image.Height);
+                    int y2 = random.Next(image.Height);
+                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
+                }
+                Font[] fonts = { new Font("Arial", 22, FontStyle.Bold | FontStyle.Italic), new Font("微软雅黑", 22, FontStyle.Bold | FontStyle.Italic), new Font("黑体", 22, FontStyle.Bold | FontStyle.Italic), new Font("宋体", 22, FontStyle.Bold | FontStyle.Italic), new Font("楷体", 22, FontStyle.Bold | FontStyle.Italic) };
+                //渐变.
+                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
+                    Color.Blue, Color.DarkRed, 1.2f, true);
+                g.DrawString(validateCode, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
+
+                //画图片的前景干扰点
+                for (int i = 0; i < 300; i++)
+                {
+                    int x = random.Next(image.Width);
+                    int y = random.Next(image.Height);
+                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
+                }
+                //画图片的边框线
+                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
+                //保存图片数据
+                MemoryStream stream = new MemoryStream();
+                image.Save(stream, ImageFormat.Jpeg);
+                //输出图片流
+                context.Response.Clear();
+                context.Response.ContentType = "image/jpeg";
+                context.Response.BinaryWrite(stream.ToArray());
+            }
+            finally
+            {
+                g.Dispose();
+                image.Dispose();
+            }
+        }
+
+        /// <summary>
+        /// 得到验证码图片的长度
+        /// </summary>
+        /// <param name="validateNumLength">验证码的长度</param>
+        /// <returns></returns>
+        public static int GetImageWidth(int validateNumLength)
+        {
+            return (int)(validateNumLength * 12.0);
+        }
+
+        /// <summary>
+        /// 得到验证码的高度
+        /// </summary>
+        /// <returns></returns>
+        public static double GetImageHeight()
+        {
+            return 22.5;
+        }
+    }
+}

+ 11 - 0
Masuit.Tools/app.config

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+	<runtime>
+		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+			<dependentAssembly>
+				<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
+				<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
+			</dependentAssembly>
+		</assemblyBinding>
+	</runtime>
+</configuration>

+ 14 - 0
Masuit.Tools/packages.config

@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Aspose.Words" version="17.2.0" targetFramework="net45" />
+  <package id="ConDep.Dsl" version="4.0.7" targetFramework="net45" />
+  <package id="log4net" version="2.0.0" targetFramework="net45" />
+  <package id="Microsoft.AspNet.WebApi.Client" version="4.0.30506.0" targetFramework="net45" />
+  <package id="Microsoft.Bcl" version="1.1.10" targetFramework="net45" />
+  <package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="net45" />
+  <package id="Microsoft.Net.Http" version="2.2.29" targetFramework="net45" />
+  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
+  <package id="SharpZipLib" version="0.86.0" targetFramework="net45" />
+  <package id="SlowCheetah.Tasks.Unofficial" version="1.0.0" targetFramework="net45" />
+  <package id="StackExchange.Redis" version="1.2.0" targetFramework="net45" />
+</packages>

+ 2 - 0
Masuit.Tools帮助文档/ContentLayout.content

@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Topics />

BIN
Masuit.Tools帮助文档/Help/Masuit.Tools帮助文档.chm


+ 74 - 0
Masuit.Tools帮助文档/Masuit.Tools帮助文档.shfbproj

@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
+  <PropertyGroup>
+    <!-- The configuration and platform will be used to determine which assemblies to include from solution and
+				 project documentation sources -->
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>9960a20a-7bad-4125-b93c-bca3906ebcc1</ProjectGuid>
+    <SHFBSchemaVersion>1.9.9.0</SHFBSchemaVersion>
+    <!-- AssemblyName, Name, and RootNamespace are not used by SHFB but Visual Studio adds them anyway -->
+    <AssemblyName>Masuit.Tools帮助文档</AssemblyName>
+    <RootNamespace>Masuit.Tools帮助文档</RootNamespace>
+    <Name>Masuit.Tools帮助文档</Name>
+    <!-- SHFB properties -->
+    <FrameworkVersion>.NET Framework 4.0</FrameworkVersion>
+    <OutputPath>.\Help\</OutputPath>
+    <HtmlHelpName>Masuit.Tools帮助文档</HtmlHelpName>
+    <Language>zh-CHS</Language>
+    <TransformComponentArguments>
+      <Argument Key="logoFile" Value="Help.png" xmlns="" />
+      <Argument Key="logoHeight" Value="" xmlns="" />
+      <Argument Key="logoWidth" Value="" xmlns="" />
+      <Argument Key="logoAltText" Value="" xmlns="" />
+      <Argument Key="logoPlacement" Value="left" xmlns="" />
+      <Argument Key="logoAlignment" Value="left" xmlns="" />
+      <Argument Key="maxVersionParts" Value="" xmlns="" />
+    </TransformComponentArguments>
+    <DocumentationSources>
+      <DocumentationSource sourceFile="..\Masuit.Utilities\bin\Debug\Masuit.Tools.XML" xmlns="" />
+      <DocumentationSource sourceFile="..\Masuit.Utilities\bin\Debug\Masuit.Tools.dll" xmlns="" />
+    </DocumentationSources>
+    <MaximumGroupParts>2</MaximumGroupParts>
+    <NamespaceGrouping>False</NamespaceGrouping>
+    <SyntaxFilters>C#</SyntaxFilters>
+    <SdkLinkTarget>Blank</SdkLinkTarget>
+    <RootNamespaceContainer>False</RootNamespaceContainer>
+    <PresentationStyle>VS2013</PresentationStyle>
+    <Preliminary>False</Preliminary>
+    <NamingMethod>MemberName</NamingMethod>
+    <HelpTitle>Masuit.Tools帮助文档</HelpTitle>
+    <ContentPlacement>AboveNamespaces</ContentPlacement>
+  </PropertyGroup>
+  <!-- There are no properties for these groups.  AnyCPU needs to appear in order for Visual Studio to perform
+			 the build.  The others are optional common platform types that may appear. -->
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Win32' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Win32' ">
+  </PropertyGroup>
+  <ItemGroup>
+    <Folder Include="icons" />
+    <Folder Include="Media" />
+  </ItemGroup>
+  <ItemGroup>
+    <ContentLayout Include="ContentLayout.content" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="icons\Help.png" />
+  </ItemGroup>
+  <!-- Import the SHFB build targets -->
+  <Import Project="$(SHFBROOT)\SandcastleHelpFileBuilder.targets" />
+</Project>

BIN
Masuit.Tools帮助文档/icons/Help.png


+ 44 - 0
MasuitTools/MasuitTools.nuproj

@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|AnyCPU">
+      <Configuration>Debug</Configuration>
+      <Platform>AnyCPU</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|AnyCPU">
+      <Configuration>Release</Configuration>
+      <Platform>AnyCPU</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\Masuit.Utilities\Masuit.Tools.csproj" />
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>eb6cc774-090e-4102-a8b2-d8e11ebebdd7</ProjectGuid>
+  </PropertyGroup>
+  <PropertyGroup>
+    <NuProjPath Condition=" '$(NuProjPath)' == '' ">$(MSBuildExtensionsPath)\NuProj\</NuProjPath>
+  </PropertyGroup>
+  <Import Project="$(NuProjPath)\NuProj.props" Condition="Exists('$(NuProjPath)\NuProj.props')" />
+  <PropertyGroup Label="Configuration">
+    <Id>Masuit.Tools</Id>
+    <Version>1.0.4</Version>
+    <Title>Masuit.Tools</Title>
+    <Authors>懒得勤快</Authors>
+    <Owners>QQ:1170397736</Owners>
+    <Summary>包含一些常用的操作类,加密解密,大文件拷贝,图像裁剪,验证码</Summary>
+    <Description>包含一些常用的操作类,大都是静态类,加密解密,反射操作,硬件信息,文档转换,字符串扩展方法,日期时间扩展操作,大文件拷贝,图像裁剪,验证码等常用封装。</Description>
+    <ReleaseNotes>QQ:1170397736</ReleaseNotes>
+    <ProjectUrl>
+    </ProjectUrl>
+    <LicenseUrl>
+    </LicenseUrl>
+    <Copyright>Copyright © 懒得勤快</Copyright>
+    <Tags>Masuit.Tools</Tags>
+    <RequireLicenseAcceptance>false</RequireLicenseAcceptance>
+    <DevelopmentDependency>true</DevelopmentDependency>
+    <EmbedSourceFiles>true</EmbedSourceFiles>
+    <OutputPath>E:\packages</OutputPath>
+  </PropertyGroup>
+  <Import Project="$(NuProjPath)\NuProj.targets" />
+</Project>

+ 6 - 0
Test/App.config

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <startup> 
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
+    </startup>
+</configuration>

+ 20 - 0
Test/Program.cs

@@ -0,0 +1,20 @@
+using System;
+
+namespace Test
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            //using (FileStream fs = new FileStream(@"G:\所有表情.eif", FileMode.OpenOrCreate, FileAccess.ReadWrite))
+            //{
+            //    fs.CopyToFileAsync(@"G:\所有表情2.eif");
+            //    Console.WriteLine(fs.GetFileMD5());
+            //    Console.WriteLine(fs.GetFileSha1());
+
+            //}
+
+            Console.ReadKey();
+        }
+    }
+}

+ 36 - 0
Test/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("Test")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Test")]
+[assembly: AssemblyCopyright("Copyright ©  2017")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+//将 ComVisible 设置为 false 将使此程序集中的类型
+//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+[assembly: Guid("06a73840-0809-4747-9760-7ef65a284c2b")]
+
+// 程序集的版本信息由下列四个值组成: 
+//
+//      主版本
+//      次版本
+//      生成号
+//      修订号
+//
+//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: :
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 65 - 0
Test/Test.csproj

@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{06A73840-0809-4747-9760-7EF65A284C2B}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Test</RootNamespace>
+    <AssemblyName>Test</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\Masuit.Tools\Masuit.Tools.csproj">
+      <Project>{275d5a0d-c49c-497e-a4b5-f40285c2495f}</Project>
+      <Name>Masuit.Tools</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>