你的位置:首页 > ASP.net教程

[ASP.net教程]【C#公共帮助类】 ToolsHelper帮助类


这个帮助类,目前我们只用到了两个,我就先更新这两个,后面有用到的,我会继续更新这个Helper帮助类

在Tools.cs中 有很多方法 跟Utils里是重复的,而且Utils里的方法更加新一点,大家可以删除Tools.cs里重复的,我只是删除了部分重复的。

RegexHelper

 

 1 using System.Text.RegularExpressions; 2  3 namespace Common 4 { 5   /// <summary> 6   /// 操作正则表达式的公共类 7   /// </summary>   8   public class RegexHelper 9   {10     #region 验证输入字符串是否与模式字符串匹配11     /// <summary>12     /// 验证输入字符串是否与模式字符串匹配,匹配返回true13     /// </summary>14     /// <param name="input">输入字符串</param>15     /// <param name="pattern">模式字符串</param>    16     public static bool IsMatch(string input, string pattern)17     {18       return IsMatch(input, pattern, RegexOptions.IgnoreCase);19     }20 21     /// <summary>22     /// 验证输入字符串是否与模式字符串匹配,匹配返回true23     /// </summary>24     /// <param name="input">输入的字符串</param>25     /// <param name="pattern">模式字符串</param>26     /// <param name="options">筛选条件</param>27     public static bool IsMatch(string input, string pattern, RegexOptions options)28     {29       return Regex.IsMatch(input, pattern, options);30     }31     #endregion32   }33 }

View Code

 

 

Tools

 

 1 using System; 2 using System.Text; 3 using System.Text.RegularExpressions; 4 using System.Collections.Generic; 5 using System.Reflection; 6 using System.Web; 7 using System.Web.Mvc; 8 using System.ComponentModel; 9  10 namespace Common 11 { 12   /// <summary> 13   /// 功能描述:共用工具类 14   /// </summary> 15   public static class Tools 16   { 17       18     #region 得到字符串长度,一个汉字长度为2 19     /// <summary> 20     /// 得到字符串长度,一个汉字长度为2 21     /// </summary> 22     /// <param name="inputString">参数字符串</param> 23     /// <returns></returns> 24     public static int StrLength(string inputString) 25     { 26       System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); 27       int tempLen = 0; 28       byte[] s = ascii.GetBytes(inputString); 29       for (int i = 0; i < s.Length; i++) 30       { 31         if ((int)s[i] == 63) 32           tempLen += 2; 33         else 34           tempLen += 1; 35       } 36       return tempLen; 37     } 38     #endregion 39  40     #region 截取指定长度字符串 41     /// <summary> 42     /// 截取指定长度字符串 43     /// </summary> 44     /// <param name="inputString">要处理的字符串</param> 45     /// <param name="len">指定长度</param> 46     /// <returns>返回处理后的字符串</returns> 47     public static string ClipString(string inputString, int len) 48     { 49       bool isShowFix = false; 50       if (len % 2 == 1) 51       { 52         isShowFix = true; 53         len--; 54       } 55       System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); 56       int tempLen = 0; 57       string tempString = ""; 58       byte[] s = ascii.GetBytes(inputString); 59       for (int i = 0; i < s.Length; i++) 60       { 61         if ((int)s[i] == 63) 62           tempLen += 2; 63         else 64           tempLen += 1; 65  66         try 67         { 68           tempString += inputString.Substring(i, 1); 69         } 70         catch 71         { 72           break; 73         } 74  75         if (tempLen > len) 76           break; 77       } 78  79       byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); 80       if (isShowFix && mybyte.Length > len) 81         tempString += "…"; 82       return tempString; 83     } 84     #endregion 85  86     #region 获得两个日期的间隔 87     /// <summary> 88     /// 获得两个日期的间隔 89     /// </summary> 90     /// <param name="DateTime1">日期一。</param> 91     /// <param name="DateTime2">日期二。</param> 92     /// <returns>日期间隔TimeSpan。</returns> 93     public static TimeSpan DateDiff(DateTime DateTime1, DateTime DateTime2) 94     { 95       TimeSpan ts1 = new TimeSpan(DateTime1.Ticks); 96       TimeSpan ts2 = new TimeSpan(DateTime2.Ticks); 97       TimeSpan ts = ts1.Subtract(ts2).Duration(); 98       return ts; 99     }100     #endregion101 102     #region 格式化日期时间103     /// <summary>104     /// 格式化日期时间105     /// </summary>106     /// <param name="dateTime1">日期时间</param>107     /// <param name="dateMode">显示模式</param>108     /// <returns>0-9种模式的日期</returns>109     public static string FormatDate(DateTime dateTime1, string dateMode)110     {111       switch (dateMode)112       {113         case "0":114           return dateTime1.ToString("yyyy-MM-dd");115         case "1":116           return dateTime1.ToString("yyyy-MM-dd HH:mm:ss");117         case "2":118           return dateTime1.ToString("yyyy/MM/dd");119         case "3":120           return dateTime1.ToString("yyyy年MM月dd日");121         case "4":122           return dateTime1.ToString("MM-dd");123         case "5":124           return dateTime1.ToString("MM/dd");125         case "6":126           return dateTime1.ToString("MM月dd日");127         case "7":128           return dateTime1.ToString("yyyy-MM");129         case "8":130           return dateTime1.ToString("yyyy/MM");131         case "9":132           return dateTime1.ToString("yyyy年MM月");133         default:134           return dateTime1.ToString();135       }136     }137     #endregion138 139     #region 得到随机日期140     /// <summary>141     /// 得到随机日期142     /// </summary>143     /// <param name="time1">起始日期</param>144     /// <param name="time2">结束日期</param>145     /// <returns>间隔日期之间的 随机日期</returns>146     public static DateTime GetRandomTime(DateTime time1, DateTime time2)147     {148       Random random = new Random();149       DateTime minTime = new DateTime();150       DateTime maxTime = new DateTime();151 152       System.TimeSpan ts = new System.TimeSpan(time1.Ticks - time2.Ticks);153 154       // 获取两个时间相隔的秒数155       double dTotalSecontds = ts.TotalSeconds;156       int iTotalSecontds = 0;157 158       if (dTotalSecontds > System.Int32.MaxValue)159       {160         iTotalSecontds = System.Int32.MaxValue;161       }162       else if (dTotalSecontds < System.Int32.MinValue)163       {164         iTotalSecontds = System.Int32.MinValue;165       }166       else167       {168         iTotalSecontds = (int)dTotalSecontds;169       }170 171 172       if (iTotalSecontds > 0)173       {174         minTime = time2;175         maxTime = time1;176       }177       else if (iTotalSecontds < 0)178       {179         minTime = time1;180         maxTime = time2;181       }182       else183       {184         return time1;185       }186 187       int maxValue = iTotalSecontds;188 189       if (iTotalSecontds <= System.Int32.MinValue)190         maxValue = System.Int32.MinValue + 1;191 192       int i = random.Next(System.Math.Abs(maxValue));193 194       return minTime.AddSeconds(i);195     }196     /// <summary>197     /// 获取时间戳198     /// </summary>199     public static string GetRandomTimeSpan()200     {201       TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);202       return Convert.ToInt64(ts.TotalSeconds).ToString();203     }204     #endregion205 206     #region HTML转行成TEXT207     /// <summary>208     /// HTML转行成TEXT209     /// </summary>210     /// <param name="strHtml"></param>211     /// <returns></returns>212     public static string HtmlToTxt(string strHtml)213     {214       string[] aryReg ={215       @"<script[^>]*?>.*?</script>",216       @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",217       @"([\r\n])[\s]+",218       @"&(quot|#34);",219       @"&(amp|#38);",220       @"&(lt|#60);",221       @"&(gt|#62);", 222       @"&(nbsp|#160);", 223       @"&(iexcl|#161);",224       @"&(cent|#162);",225       @"&(pound|#163);",226       @"&(copy|#169);",227       @"&#(\d+);",228       @"-->",229       @"<!--.*\n"230       };231 232       string newReg = aryReg[0];233       string strOutput = strHtml;234       for (int i = 0; i < aryReg.Length; i++)235       {236         Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);237         strOutput = regex.Replace(strOutput, string.Empty);238       }239 240       strOutput.Replace("<", "");241       strOutput.Replace(">", "");242       strOutput.Replace("\r\n", "");243 244 245       return strOutput;246     }247     #endregion248 249     #region 判断对象是否为空250     /// <summary>251     /// 判断对象是否为空,为空返回true252     /// </summary>253     /// <typeparam name="T">要验证的对象的类型</typeparam>254     /// <param name="data">要验证的对象</param>    255     public static bool IsNullOrEmpty<T>(this T data)256     {257       //如果为null258       if (data == null)259       {260         return true;261       }262 263       //如果为""264       if (data.GetType() == typeof(String))265       {266         if (string.IsNullOrEmpty(data.ToString().Trim()) || data.ToString() == "")267         {268           return true;269         }270       }271 272       //如果为DBNull273       if (data.GetType() == typeof(DBNull))274       {275         return true;276       }277 278       //不为空279       return false;280     }281 282     /// <summary>283     /// 判断对象是否为空,为空返回true284     /// </summary>285     /// <param name="data">要验证的对象</param>286     public static bool IsNullOrEmpty(this object data)287     {288       //如果为null289       if (data == null)290       {291         return true;292       }293 294       //如果为""295       if (data.GetType() == typeof(String))296       {297         if (string.IsNullOrEmpty(data.ToString().Trim()))298         {299           return true;300         }301       }302 303       //如果为DBNull304       if (data.GetType() == typeof(DBNull))305       {306         return true;307       }308 309       //不为空310       return false;311     }312     #endregion   313 314     #region 验证是否为浮点数315     /// <summary>316     /// 验证是否浮点数317     /// </summary>318     /// <param name="floatNum"></param>319     /// <returns></returns>320     public static bool IsFloat(this string floatNum)321     {322       //如果为空,认为验证不合格323       if (IsNullOrEmpty(floatNum))324       {325         return false;326       }327       //清除要验证字符串中的空格328       floatNum = floatNum.Trim();329 330       //模式字符串331       string pattern = @"^(-?\d+)(\.\d+)?$";332 333       //验证334       return RegexHelper.IsMatch(floatNum, pattern);335     }336     #endregion337 338     #region 验证是否为整数339     /// <summary>340     /// 验证是否为整数 如果为空,认为验证不合格 返回false341     /// </summary>342     /// <param name="number">要验证的整数</param>    343     public static bool IsInt(this string number)344     {345       //如果为空,认为验证不合格346       if (IsNullOrEmpty(number))347       {348         return false;349       }350 351       //清除要验证字符串中的空格352       number = number.Trim();353 354       //模式字符串355       string pattern = @"^[0-9]+[0-9]*$";356 357       //验证358       return RegexHelper.IsMatch(number, pattern);359     }360     #endregion361 362     #region 验证是否为数字363     /// <summary>364     /// 验证是否为数字365     /// </summary>366     /// <param name="number">要验证的数字</param>    367     public static bool IsNumber(this string number)368     {369       //如果为空,认为验证不合格370       if (IsNullOrEmpty(number))371       {372         return false;373       }374 375       //清除要验证字符串中的空格376       number = number.Trim();377 378       //模式字符串379       string pattern = @"^[0-9]+[0-9]*[.]?[0-9]*$";380 381       //验证382       return RegexHelper.IsMatch(number, pattern);383     }384     #endregion385 386     #region 验证日期是否合法387     /// <summary>388     /// 是否是日期389     /// </summary>390     /// <param name="date"></param>391     /// <returns></returns>392     public static bool IsDate(this object date)393     {394 395       //如果为空,认为验证合格396       if (IsNullOrEmpty(date))397       {398         return false;399       }400       string strdate = date.ToString();401       try402       {403         //用转换测试是否为规则的日期字符404         date = Convert.ToDateTime(date).ToString("d");405         return true;406       }407       catch408       {409         //如果日期字符串中存在非数字,则返回false410         if (!IsInt(strdate))411         {412           return false;413         }414 415         #region 对纯数字进行解析416         //对8位纯数字进行解析417         if (strdate.Length == 8)418         {419           //获取年月日420           string year = strdate.Substring(0, 4);421           string month = strdate.Substring(4, 2);422           string day = strdate.Substring(6, 2);423 424           //验证合法性425           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)426           {427             return false;428           }429           if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)430           {431             return false;432           }433 434           //拼接日期435           date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");436           return true;437         }438 439         //对6位纯数字进行解析440         if (strdate.Length == 6)441         {442           //获取年月443           string year = strdate.Substring(0, 4);444           string month = strdate.Substring(4, 2);445 446           //验证合法性447           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)448           {449             return false;450           }451           if (Convert.ToInt32(month) > 12)452           {453             return false;454           }455 456           //拼接日期457           date = Convert.ToDateTime(year + "-" + month).ToString("d");458           return true;459         }460 461         //对5位纯数字进行解析462         if (strdate.Length == 5)463         {464           //获取年月465           string year = strdate.Substring(0, 4);466           string month = strdate.Substring(4, 1);467 468           //验证合法性469           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)470           {471             return false;472           }473 474           //拼接日期475           date = year + "-" + month;476           return true;477         }478 479         //对4位纯数字进行解析480         if (strdate.Length == 4)481         {482           //获取年483           string year = strdate.Substring(0, 4);484 485           //验证合法性486           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)487           {488             return false;489           }490 491           //拼接日期492           date = Convert.ToDateTime(year).ToString("d");493           return true;494         }495         #endregion496 497         return false;498       }499 500     }501     /// <summary>502     /// 验证日期是否合法,对不规则的作了简单处理503     /// </summary>504     /// <param name="date">日期</param>505     public static bool IsDate(ref string date)506     {507       //如果为空,认为验证合格508       if (IsNullOrEmpty(date))509       {510         return true;511       }512 513       //清除要验证字符串中的空格514       date = date.Trim();515 516       //替换\517       date = date.Replace(@"\", "-");518       //替换/519       date = date.Replace(@"/", "-");520 521       //如果查找到汉字"今",则认为是当前日期522       if (date.IndexOf("今") != -1)523       {524         date = DateTime.Now.ToString();525       }526 527       try528       {529         //用转换测试是否为规则的日期字符530         date = Convert.ToDateTime(date).ToString("d");531         return true;532       }533       catch534       {535         //如果日期字符串中存在非数字,则返回false536         if (!IsInt(date))537         {538           return false;539         }540 541         #region 对纯数字进行解析542         //对8位纯数字进行解析543         if (date.Length == 8)544         {545           //获取年月日546           string year = date.Substring(0, 4);547           string month = date.Substring(4, 2);548           string day = date.Substring(6, 2);549 550           //验证合法性551           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)552           {553             return false;554           }555           if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)556           {557             return false;558           }559 560           //拼接日期561           date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");562           return true;563         }564 565         //对6位纯数字进行解析566         if (date.Length == 6)567         {568           //获取年月569           string year = date.Substring(0, 4);570           string month = date.Substring(4, 2);571 572           //验证合法性573           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)574           {575             return false;576           }577           if (Convert.ToInt32(month) > 12)578           {579             return false;580           }581 582           //拼接日期583           date = Convert.ToDateTime(year + "-" + month).ToString("d");584           return true;585         }586 587         //对5位纯数字进行解析588         if (date.Length == 5)589         {590           //获取年月591           string year = date.Substring(0, 4);592           string month = date.Substring(4, 1);593 594           //验证合法性595           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)596           {597             return false;598           }599 600           //拼接日期601           date = year + "-" + month;602           return true;603         }604 605         //对4位纯数字进行解析606         if (date.Length == 4)607         {608           //获取年609           string year = date.Substring(0, 4);610 611           //验证合法性612           if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)613           {614             return false;615           }616 617           //拼接日期618           date = Convert.ToDateTime(year).ToString("d");619           return true;620         }621         #endregion622 623         return false;624       }625     }626     #endregion627 628     /// <summary>629     /// //前台显示邮箱的掩码替换(由tzh@qq.com等替换成t*****@qq.com)630     /// </summary>631     /// <param name="Email">邮箱</param>632     /// <returns></returns>633     public static string GetEmail(string Email)634     {635 636       string strArg = "";637       string SendEmail = "";638       Match match = Regex.Match(Email, @"(\w)\w+@");639 640       if (match.Success)641       {642         strArg = match.Groups[1].Value + "*****@";643         SendEmail = Regex.Replace(Email, @"\w+@", strArg);644       }645       else646         SendEmail = Email;647       return SendEmail;648     }649 650     /// <summary>651     /// 检查字符串是否存在与一个,组合到一起的字符串数组中652     /// </summary>653     /// <param name="strSplit">未分割的字符串</param>654     /// <param name="split">分割符号</param>655     /// <param name="targetValue">目标字符串</param>656     /// <returns></returns>657     public static bool CheckStringHasValue(string strSplit, char split, string targetValue)658     {659       string[] strList = strSplit.Split(split);660       foreach (string str in strList)661       {662         if (targetValue == str)663           return true;664       }665       return false;666     }667 668     #region 枚举型相关操作669 670     /// <summary>671     /// 功能描述;获取枚举名称.传入枚举类型和枚举值672     /// </summary>673     /// <param name="enumType"></param>674     /// <param name="intEnumValue"></param>675     /// <returns></returns>676     public static string GetEnumText<T>(int intEnumValue)677     {678       return Enum.GetName(typeof(T), intEnumValue);679     }680 681     /// <summary>682     /// 功能描述:获取枚举项集合,传入枚举类型683     /// </summary>684     /// <typeparam name="T"></typeparam>685     /// <returns></returns>686     public static IList<object> BindEnums<T>()687     {688       IList<object> _list = new List<object>();689       //遍历枚举集合690       foreach (int i in Enum.GetValues(typeof(T)))691       {692         var _selItem = new693         {694           Value = i,695           Text = Enum.GetName(typeof(T), i)696         };697         _list.Add(_selItem);698       }699       return _list;700     }701    702     ///<summary>703     /// 返回 Dic 枚举项,描述704     ///</summary>705     ///<param name="enumType"></param>706     ///<returns>Dic枚举项,描述</returns>707     public static Dictionary<string, string> BindEnums(Type enumType)708     {709       Dictionary<string, string> dic = new Dictionary<string, string>();710       FieldInfo[] fieldinfos = enumType.GetFields();711       foreach (FieldInfo field in fieldinfos)712       {713         if (field.FieldType.IsEnum)714         {715           Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);716 717           dic.Add(field.Name, ((DescriptionAttribute)objs[0]).Description);718         }719 720       }721 722       return dic;723     }724     ///<summary>725     /// 返回 List《Enums.EnumsClass》 枚举值、名称、描述726     ///</summary>727     public static List<Enums.EnumsClass> BindEnumsList(Type enumType)728     {729       var list = new List<Enums.EnumsClass>();730       FieldInfo[] fieldinfos = enumType.GetFields();731       var enumvalue = Enum.GetValues(enumType);732       foreach (FieldInfo field in fieldinfos)733       {734         if (field.FieldType.IsEnum)735         {736           int ev = -1;737           Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);738           foreach (int item in enumvalue)739           {740             if (Enum.GetName(enumType, item) == field.Name)741             {742               ev = item;743               break;744             }745           }746           list.Add(new Enums.EnumsClass747           {748             Name = field.Name,749             Value = ev,750             Text = ((DescriptionAttribute)objs[0]).Description751           });752         }753       }754       return list;755     }756 757     #endregion758 759     #region 获取集合中某个字段的拼接,例:获取姓名拼接760 761     /// <summary>762     /// 功能描述:获取集合中某个字段的拼接,例:获取姓名拼接763     /// </summary>764     /// <typeparam name="T"></typeparam>765     /// <param name="list">集合</param>766     /// <param name="strFieldName">字段名</param>767     /// <param name="strSplit">分隔符</param>768     /// <returns></returns>769     public static string GetFieldValueJoin<T>(IList<T> list, string strFieldName, string strSplit)770     {771       //判断入口772       if (list == null || list.Count <= 0 || string.IsNullOrEmpty(strFieldName))773         return string.Empty;774 775 776       //获取属性777       PropertyInfo _pro = typeof(T).GetProperty(strFieldName);778       if (_pro == null)779         return string.Empty;780       //变量,记录返回值781       string _strReturn = string.Empty;782       foreach (T _entityI in list)783       {784         //获取属性值785         object _objValue = _pro.GetValue(_entityI, null);786         if (_objValue == null || string.IsNullOrEmpty(_objValue.ToString()))787           //没有属性值,则跳过788           continue;789 790         //有属性值,则拼接791         _strReturn += _objValue.ToString() + strSplit;792       }793 794       if (string.IsNullOrEmpty(_strReturn))795         return string.Empty;796 797       return _strReturn.Substring(0, _strReturn.Length - strSplit.Length);798     }799 800     #endregion801 802    803 804   }805 }

View Code

 

 

原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com