c# 工具类(字符串和时间,文件)

时间:2023-03-08 19:22:10
c# 工具类(字符串和时间,文件)
  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. using System.Windows.Browser;
  5. namespace SL_COMMON
  6. {
  7. public class Utils
  8. {
  9. #region String字符串类
  10. /**/
  11. /// <summary>
  12. /// 过滤字符
  13. /// </summary>
  14. public static string Replace(string strOriginal, string oldchar, string newchar)
  15. {
  16. if (string.IsNullOrEmpty(strOriginal))
  17. return "";
  18. string tempChar = strOriginal;
  19. tempChar = tempChar.Replace(oldchar, newchar);
  20. return tempChar;
  21. }
  22. /**/
  23. /// <summary>
  24. /// 过滤非法字符
  25. /// </summary>
  26. /// <param name="str"></param>
  27. /// <returns></returns>
  28. public static string ReplaceBadChar(string str)
  29. {
  30. if (string.IsNullOrEmpty(str))
  31. return "";
  32. string strBadChar, tempChar;
  33. string[] arrBadChar;
  34. strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\",";
  35. arrBadChar = SplitString(strBadChar, ",");
  36. tempChar = str;
  37. for (int i = 0; i < arrBadChar.Length; i++)
  38. {
  39. if (arrBadChar[i].Length > 0)
  40. tempChar = tempChar.Replace(arrBadChar[i], "");
  41. }
  42. return tempChar;
  43. }
  44. /**/
  45. /// <summary>
  46. /// 检查是否含有非法字符
  47. /// </summary>
  48. /// <param name="str">要检查的字符串</param>
  49. /// <returns></returns>
  50. public static bool ChkBadChar(string str)
  51. {
  52. bool result = false;
  53. if (string.IsNullOrEmpty(str))
  54. return result;
  55. string strBadChar, tempChar;
  56. string[] arrBadChar;
  57. strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\"";
  58. arrBadChar = SplitString(strBadChar, ",");
  59. tempChar = str;
  60. for (int i = 0; i < arrBadChar.Length; i++)
  61. {
  62. if (tempChar.IndexOf(arrBadChar[i]) >= 0)
  63. result = true;
  64. }
  65. return result;
  66. }
  67. /**/
  68. /// <summary>
  69. /// 分割字符串
  70. /// </summary>
  71. public static string[] SplitString(string strContent, string strSplit)
  72. {
  73. if (string.IsNullOrEmpty(strContent))
  74. {
  75. return null;
  76. }
  77. int i = strContent.IndexOf(strSplit);
  78. if (strContent.IndexOf(strSplit) < 0)
  79. {
  80. string[] tmp = { strContent };
  81. return tmp;
  82. }
  83. //return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
  84. return Regex.Split(strContent, @strSplit.Replace(".", @"\."));
  85. }
  86. /**/
  87. /// <summary>
  88. /// string型转换为int型
  89. /// </summary>
  90. /// <param name="strValue">要转换的字符串</param>
  91. /// <returns>转换后的int类型结果.如果要转换的字符串是非数字,则返回-1.</returns>
  92. public static int StrToInt(object strValue)
  93. {
  94. int defValue = -1;
  95. if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10))
  96. {
  97. return defValue;
  98. }
  99. string val = strValue.ToString();
  100. string firstletter = val[0].ToString();
  101. if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1)
  102. {
  103. return defValue;
  104. }
  105. else if (val.Length == 10 && !IsNumber(firstletter))
  106. {
  107. return defValue;
  108. }
  109. int intValue = defValue;
  110. if (strValue != null)
  111. {
  112. bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString());
  113. if (IsInt)
  114. {
  115. intValue = Convert.ToInt32(strValue);
  116. }
  117. }
  118. return intValue;
  119. }
  120. /**/
  121. /// <summary>
  122. /// string型转换为int型
  123. /// </summary>
  124. /// <param name="strValue">要转换的字符串</param>
  125. /// <param name="defValue">缺省值</param>
  126. /// <returns>转换后的int类型结果</returns>
  127. public static int StrToInt(object strValue, int defValue)
  128. {
  129. if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10))
  130. {
  131. return defValue;
  132. }
  133. string val = strValue.ToString();
  134. string firstletter = val[0].ToString();
  135. if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1)
  136. {
  137. return defValue;
  138. }
  139. else if (val.Length == 10 && !IsNumber(firstletter))
  140. {
  141. return defValue;
  142. }
  143. int intValue = defValue;
  144. if (strValue != null)
  145. {
  146. bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString());
  147. if (IsInt)
  148. {
  149. intValue = Convert.ToInt32(strValue);
  150. }
  151. }
  152. return intValue;
  153. }
  154. /**/
  155. /// <summary>
  156. /// string型转换为时间型
  157. /// </summary>
  158. /// <param name="strValue">要转换的字符串</param>
  159. /// <param name="defValue">缺省值</param>
  160. /// <returns>转换后的时间类型结果</returns>
  161. public static DateTime StrToDateTime(object strValue, DateTime defValue)
  162. {
  163. if ((strValue == null) || (strValue.ToString().Length > 20))
  164. {
  165. return defValue;
  166. }
  167. DateTime intValue;
  168. if (!DateTime.TryParse(strValue.ToString(), out intValue))
  169. {
  170. intValue = defValue;
  171. }
  172. return intValue;
  173. }
  174. /**/
  175. /// <summary>
  176. /// 判断给定的字符串(strNumber)是否是数值型
  177. /// </summary>
  178. /// <param name="strNumber">要确认的字符串</param>
  179. /// <returns>是则返加true 不是则返回 false</returns>
  180. public static bool IsNumber(string strNumber)
  181. {
  182. return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber);
  183. }
  184. /**/
  185. /// <summary>
  186. /// 检测是否符合email格式
  187. /// </summary>
  188. /// <param name="strEmail">要判断的email字符串</param>
  189. /// <returns>判断结果</returns>
  190. public static bool IsValidEmail(string strEmail)
  191. {
  192. return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((
    [0−9]1,3\.[0−9]1,3\.[0−9]1,3\.)|(([\w−]+\.)+))([a−zA−Z]2,4|[0−9]1,3)(

    ?)$");

  193. }
  194. /**/
  195. /// <summary>
  196. /// 检测是否符合url格式,前面必需含有http://
  197. /// </summary>
  198. /// <param name="url"></param>
  199. /// <returns></returns>
  200. public static bool IsURL(string url)
  201. {
  202. return Regex.IsMatch(url, @"^http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$");
  203. }
  204. /**/
  205. /// <summary>
  206. /// 检测是否符合电话格式
  207. /// </summary>
  208. /// <param name="phoneNumber"></param>
  209. /// <returns></returns>
  210. public static bool IsPhoneNumber(string phoneNumber)
  211. {
  212. |\d{3}-)?\d{7,8}$");
  213. }
  214. /**/
  215. /// <summary>
  216. /// 检测是否符合身份证号码格式
  217. /// </summary>
  218. /// <param name="num"></param>
  219. /// <returns></returns>
  220. public static bool IsIdentityNumber(string num)
  221. {
  222. return Regex.IsMatch(num, @"^\d{17}[\d|X]|\d{15}$");
  223. }
  224. #endregion
  225. #region Sql类
  226. /**/
  227. /// <summary>
  228. /// 检测是否有Sql危险字符
  229. /// </summary>
  230. /// <param name="str">要判断字符串</param>
  231. /// <returns>判断结果</returns>
  232. public static bool IsSafeSqlString(string str)
  233. {
  234. return !Regex.IsMatch(str, @"[-|;|,|\/|||
    |

    |\}|\{|%|@|\*|!|\']");

  235. }
  236. /**/
  237. /// <summary>
  238. /// 替换sql语句中的单引号
  239. /// </summary>
  240. public static string ReplaceBadSQL(string str)
  241. {
  242. string str2;
  243. if (str == null)
  244. {
  245. str2 = "";
  246. }
  247. else
  248. {
  249. str = str.Replace("'", "''");
  250. str2 = str;
  251. }
  252. return str2;
  253. }
  254. #endregion
  255. #region Html类
  256. /**/
  257. /// <summary>
  258. /// 返回 HTML 字符串的解码结果
  259. /// </summary>
  260. /// <param name="str">字符串</param>
  261. /// <returns>解码结果</returns>
  262. public static string HtmlDecode(string str)
  263. {
  264. //str = str.Replace("''", "'");
  265. return HttpUtility.HtmlDecode(str);
  266. }
  267. /**/
  268. /// <summary>
  269. /// 替换html字符
  270. /// </summary>
  271. public static string EncodeHtml(string strHtml)
  272. {
  273. if (strHtml != "")
  274. {
  275. strHtml = strHtml.Replace(",", "&def");
  276. strHtml = strHtml.Replace("'", "&dot");
  277. strHtml = strHtml.Replace(";", "&dec");
  278. return strHtml;
  279. }
  280. return "";
  281. }
  282. /**/
  283. /// <summary>
  284. /// 替换回车换行符为html换行符
  285. /// </summary>
  286. public static string StrFormat(string str)
  287. {
  288. string str2;
  289. if (str == null)
  290. {
  291. str2 = "";
  292. }
  293. else
  294. {
  295. str = str.Replace("\r\n", "<br />");
  296. str = str.Replace("\n", "<br />");
  297. str2 = str;
  298. }
  299. return str2;
  300. }
  301. #endregion
  302. #region DateTime类
  303. /**/
  304. /// <summary>
  305. /// 返回当前服务器时间的 yyyy-MM-dd 日期格式string
  306. /// </summary>
  307. public static string GetDate()
  308. {
  309. return DateTime.Now.ToString("yyyy-MM-dd");
  310. }
  311. /**/
  312. /// <summary>
  313. ///返回当前服务器时间的标准时间格式string HH:mm:ss
  314. /// </summary>
  315. public static string GetTime()
  316. {
  317. return DateTime.Now.ToString("HH:mm:ss");
  318. }
  319. /**/
  320. /// <summary>
  321. /// 返回当前服务器时间的标准时间格式string yyyy-MM-dd HH:mm:ss
  322. /// </summary>
  323. public static string GetDateTime()
  324. {
  325. return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  326. }
  327. /**/
  328. /// <summary>
  329. /// 返回当前服务器时间的标准时间格式string yyyy-MM-dd HH:mm:ss:fffffff
  330. /// </summary>
  331. public static string GetDateTimeF()
  332. {
  333. return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
  334. }
  335. /**/
  336. /// <summary>
  337. /// 将string类型的fDateTime转换为formatStr格式的日期类型
  338. /// </summary>
  339. public static string GetStandardDateTime(string fDateTime, string formatStr)
  340. {
  341. DateTime s = Convert.ToDateTime(fDateTime);
  342. return s.ToString(formatStr);
  343. }
  344. /**/
  345. /// <summary>
  346. ///将string类型的fDateTime转换为日期类型 yyyy-MM-dd HH:mm:ss
  347. /// </sumary>
  348. public static string GetStandardDateTime(string fDateTime)
  349. {
  350. return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
  351. }
  352. /**/
  353. /// <summary>
  354. /// 返回相差的秒数
  355. /// </summary>
  356. /// <param name="Time"></param>
  357. /// <param name="Sec"></param>
  358. /// <returns></returns>
  359. public static int StrDateDiffSeconds(string Time, int Sec)
  360. {
  361. TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
  362. if (ts.TotalSeconds > int.MaxValue)
  363. {
  364. return int.MaxValue;
  365. }
  366. else if (ts.TotalSeconds < int.MinValue)
  367. {
  368. return int.MinValue;
  369. }
  370. return (int)ts.TotalSeconds;
  371. }
  372. /**/
  373. /// <summary>
  374. /// 返回相差的分钟数
  375. /// </summary>
  376. /// <param name="time"></param>
  377. /// <param name="minutes"></param>
  378. /// <returns></returns>
  379. public static int StrDateDiffMinutes(string time, int minutes)
  380. {
  381. if (time == "" || time == null)
  382. return 1;
  383. TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
  384. if (ts.TotalMinutes > int.MaxValue)
  385. {
  386. return int.MaxValue;
  387. }
  388. else if (ts.TotalMinutes < int.MinValue)
  389. {
  390. return int.MinValue;
  391. }
  392. return (int)ts.TotalMinutes;
  393. }
  394. /**/
  395. /// <summary>
  396. /// 返回相差的小时数
  397. /// </summary>
  398. /// <param name="time"></param>
  399. /// <param name="hours"></param>
  400. /// <returns></returns>
  401. public static int StrDateDiffHours(string time, int hours)
  402. {
  403. if (time == "" || time == null)
  404. return 1;
  405. TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
  406. if (ts.TotalHours > int.MaxValue)
  407. {
  408. return int.MaxValue;
  409. }
  410. else if (ts.TotalHours < int.MinValue)
  411. {
  412. return int.MinValue;
  413. }
  414. return (int)ts.TotalHours;
  415. }
  416. #endregion
  417. #region file类
  418. /**/
  419. /// <summary>
  420. /// 文件是否存在
  421. /// </summary>
  422. /// <param name="filePath">相对路径</param>
  423. /// <returns></returns>
  424. public static bool FileExists(string filePath)
  425. {
  426. if (string.IsNullOrEmpty(filePath))
  427. return false;
  428. filePath = HttpContext.Current.Server.MapPath(filePath);
  429. DirectoryInfo dirInfo = new DirectoryInfo(filePath);
  430. if (dirInfo.Exists)
  431. return true;
  432. return false;
  433. }
  434. #endregion
  435. }
  436. }