【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 /// 驗證輸入字符串是否與模式字符串匹配,匹配返回true
13 /// </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 /// 驗證輸入字符串是否與模式字符串匹配,匹配返回true
23 /// </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 #endregion
32 }
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 #endregion
101
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 #endregion
138
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 else
167 {
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 else
183 {
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 #endregion
205
206 #region HTML轉行成TEXT
207 /// <summary>
208 /// HTML轉行成TEXT
209 /// </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 #endregion
248
249 #region 判斷對象是否為空
250 /// <summary>
251 /// 判斷對象是否為空,為空返回true
252 /// </summary>
253 /// <typeparam name="T">要驗證的對象的類型</typeparam>
254 /// <param name="data">要驗證的對象</param>
255 public static bool IsNullOrEmpty<T>(this T data)
256 {
257 //如果為null
258 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 //如果為DBNull
273 if (data.GetType() == typeof(DBNull))
274 {
275 return true;
276 }
277
278 //不為空
279 return false;
280 }
281
282 /// <summary>
283 /// 判斷對象是否為空,為空返回true
284 /// </summary>
285 /// <param name="data">要驗證的對象</param>
286 public static bool IsNullOrEmpty(this object data)
287 {
288 //如果為null
289 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 //如果為DBNull
304 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 #endregion
337
338 #region 驗證是否為整數
339 /// <summary>
340 /// 驗證是否為整數 如果為空,認為驗證不合格 返回false
341 /// </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 #endregion
361
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 #endregion
385
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 try
402 {
403 //用轉換測試是否為規則的日期字符
404 date = Convert.ToDateTime(date).ToString("d");
405 return true;
406 }
407 catch
408 {
409 //如果日期字符串中存在非數字,則返回false
410 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 #endregion
496
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 try
528 {
529 //用轉換測試是否為規則的日期字符
530 date = Convert.ToDateTime(date).ToString("d");
531 return true;
532 }
533 catch
534 {
535 //如果日期字符串中存在非數字,則返回false
536 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 #endregion
622
623 return false;
624 }
625 }
626 #endregion
627
628 /// <summary>
629 /// //前台顯示郵箱的掩碼替換(由
[email protected]等替換成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 else
646 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 = new
693 {
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.EnumsClass
747 {
748 Name = field.Name,
749 Value = ev,
750 Text = ((DescriptionAttribute)objs[0]).Description
751 });
752 }
753 }
754 return list;
755 }
756
757 #endregion
758
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 #endregion
801
802
803
804 }
805 }
View Code
原創文章 轉載請尊重勞動成果 http://yuangang.cnblogs.com