整理项目中常用到的方法
2015-05-07 15:42 糯米粥 阅读(394) 评论(0) 编辑 收藏 举报项目中有时候会进程要用到一些重复的代码:比如MD5加密,截取字符串,读和写cookie,既然经常用到。那么就 会封装成一个类。叫工具类:utils。。
汇总如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Net; 7 using System.Web; 8 using System.Security.Cryptography; 9 using System.Text.RegularExpressions; 10 using System.Configuration; 11 12 namespace Common 13 { 14 public class Utils 15 { 16 #region MD5加密 17 public static string MD5(string pwd) 18 { 19 MD5 md5 = new MD5CryptoServiceProvider(); 20 byte[] data = System.Text.Encoding.Default.GetBytes(pwd); 21 byte[] md5data = md5.ComputeHash(data); 22 md5.Clear(); 23 string str = ""; 24 for (int i = 0; i < md5data.Length; i++) 25 { 26 str += md5data[i].ToString("x").PadLeft(2, '0'); 27 28 } 29 return str; 30 } 31 #endregion 32 33 #region 对象转换处理 34 /// <summary> 35 /// 判断对象是否为Int32类型的数字 36 /// </summary> 37 /// <param name="Expression"></param> 38 /// <returns></returns> 39 public static bool IsNumeric(object expression) 40 { 41 if (expression != null) 42 return IsNumeric(expression.ToString()); 43 44 return false; 45 46 } 47 48 /// <summary> 49 /// 判断对象是否为Int32类型的数字 50 /// </summary> 51 /// <param name="Expression"></param> 52 /// <returns></returns> 53 public static bool IsNumeric(string expression) 54 { 55 if (expression != null) 56 { 57 string str = expression; 58 if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$")) 59 { 60 if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1')) 61 return true; 62 } 63 } 64 return false; 65 } 66 67 /// <summary> 68 /// 是否为Double类型 69 /// </summary> 70 /// <param name="expression"></param> 71 /// <returns></returns> 72 public static bool IsDouble(object expression) 73 { 74 if (expression != null) 75 return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$"); 76 77 return false; 78 } 79 80 /// <summary> 81 /// 检测是否符合email格式 82 /// </summary> 83 /// <param name="strEmail">要判断的email字符串</param> 84 /// <returns>判断结果</returns> 85 public static bool IsValidEmail(string strEmail) 86 { 87 return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); 88 } 89 public static bool IsValidDoEmail(string strEmail) 90 { 91 return Regex.IsMatch(strEmail, @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 92 } 93 94 /// <summary> 95 /// 检测是否是正确的Url 96 /// </summary> 97 /// <param name="strUrl">要验证的Url</param> 98 /// <returns>判断结果</returns> 99 public static bool IsURL(string strUrl) 100 { 101 return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); 102 } 103 104 /// <summary> 105 /// 将字符串转换为数组 106 /// </summary> 107 /// <param name="str">字符串</param> 108 /// <returns>字符串数组</returns> 109 public static string[] GetStrArray(string str) 110 { 111 return str.Split(new char[',']); 112 } 113 114 /// <summary> 115 /// 将数组转换为字符串 116 /// </summary> 117 /// <param name="list">List</param> 118 /// <param name="speater">分隔符</param> 119 /// <returns>String</returns> 120 public static string GetArrayStr(List<string> list, string speater) 121 { 122 StringBuilder sb = new StringBuilder(); 123 for (int i = 0; i < list.Count; i++) 124 { 125 if (i == list.Count - 1) 126 { 127 sb.Append(list[i]); 128 } 129 else 130 { 131 sb.Append(list[i]); 132 sb.Append(speater); 133 } 134 } 135 return sb.ToString(); 136 } 137 138 /// <summary> 139 /// object型转换为bool型 140 /// </summary> 141 /// <param name="strValue">要转换的字符串</param> 142 /// <param name="defValue">缺省值</param> 143 /// <returns>转换后的bool类型结果</returns> 144 public static bool StrToBool(object expression, bool defValue) 145 { 146 if (expression != null) 147 return StrToBool(expression, defValue); 148 149 return defValue; 150 } 151 152 /// <summary> 153 /// string型转换为bool型 154 /// </summary> 155 /// <param name="strValue">要转换的字符串</param> 156 /// <param name="defValue">缺省值</param> 157 /// <returns>转换后的bool类型结果</returns> 158 public static bool StrToBool(string expression, bool defValue) 159 { 160 if (expression != null) 161 { 162 if (string.Compare(expression, "true", true) == 0) 163 return true; 164 else if (string.Compare(expression, "false", true) == 0) 165 return false; 166 } 167 return defValue; 168 } 169 170 /// <summary> 171 /// 将对象转换为Int32类型 172 /// </summary> 173 /// <param name="expression">要转换的字符串</param> 174 /// <param name="defValue">缺省值</param> 175 /// <returns>转换后的int类型结果</returns> 176 public static int ObjToInt(object expression, int defValue) 177 { 178 if (expression != null) 179 return StrToInt(expression.ToString(), defValue); 180 181 return defValue; 182 } 183 184 /// <summary> 185 /// 将字符串转换为Int32类型 186 /// </summary> 187 /// <param name="expression">要转换的字符串</param> 188 /// <param name="defValue">缺省值</param> 189 /// <returns>转换后的int类型结果</returns> 190 public static int StrToInt(string expression, int defValue) 191 { 192 if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$")) 193 return defValue; 194 195 int rv; 196 if (Int32.TryParse(expression, out rv)) 197 return rv; 198 199 return Convert.ToInt32(StrToFloat(expression, defValue)); 200 } 201 202 /// <summary> 203 /// Object型转换为decimal型 204 /// </summary> 205 /// <param name="strValue">要转换的字符串</param> 206 /// <param name="defValue">缺省值</param> 207 /// <returns>转换后的decimal类型结果</returns> 208 public static decimal ObjToDecimal(object expression, decimal defValue) 209 { 210 if (expression != null) 211 return StrToDecimal(expression.ToString(), defValue); 212 213 return defValue; 214 } 215 216 /// <summary> 217 /// string型转换为decimal型 218 /// </summary> 219 /// <param name="strValue">要转换的字符串</param> 220 /// <param name="defValue">缺省值</param> 221 /// <returns>转换后的decimal类型结果</returns> 222 public static decimal StrToDecimal(string expression, decimal defValue) 223 { 224 if ((expression == null) || (expression.Length > 10)) 225 return defValue; 226 227 decimal intValue = defValue; 228 if (expression != null) 229 { 230 bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); 231 if (IsDecimal) 232 decimal.TryParse(expression, out intValue); 233 } 234 return intValue; 235 } 236 237 /// <summary> 238 /// Object型转换为float型 239 /// </summary> 240 /// <param name="strValue">要转换的字符串</param> 241 /// <param name="defValue">缺省值</param> 242 /// <returns>转换后的int类型结果</returns> 243 public static float ObjToFloat(object expression, float defValue) 244 { 245 if (expression != null) 246 return StrToFloat(expression.ToString(), defValue); 247 248 return defValue; 249 } 250 251 /// <summary> 252 /// string型转换为float型 253 /// </summary> 254 /// <param name="strValue">要转换的字符串</param> 255 /// <param name="defValue">缺省值</param> 256 /// <returns>转换后的int类型结果</returns> 257 public static float StrToFloat(string expression, float defValue) 258 { 259 if ((expression == null) || (expression.Length > 10)) 260 return defValue; 261 262 float intValue = defValue; 263 if (expression != null) 264 { 265 bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); 266 if (IsFloat) 267 float.TryParse(expression, out intValue); 268 } 269 return intValue; 270 } 271 272 /// <summary> 273 /// 将对象转换为日期时间类型 274 /// </summary> 275 /// <param name="str">要转换的字符串</param> 276 /// <param name="defValue">缺省值</param> 277 /// <returns>转换后的int类型结果</returns> 278 public static DateTime StrToDateTime(string str, DateTime defValue) 279 { 280 if (!string.IsNullOrEmpty(str)) 281 { 282 DateTime dateTime; 283 if (DateTime.TryParse(str, out dateTime)) 284 return dateTime; 285 } 286 return defValue; 287 } 288 289 /// <summary> 290 /// 将对象转换为日期时间类型 291 /// </summary> 292 /// <param name="str">要转换的字符串</param> 293 /// <returns>转换后的int类型结果</returns> 294 public static DateTime StrToDateTime(string str) 295 { 296 return StrToDateTime(str, DateTime.Now); 297 } 298 299 /// <summary> 300 /// 将对象转换为日期时间类型 301 /// </summary> 302 /// <param name="obj">要转换的对象</param> 303 /// <returns>转换后的int类型结果</returns> 304 public static DateTime ObjectToDateTime(object obj) 305 { 306 return StrToDateTime(obj.ToString()); 307 } 308 309 /// <summary> 310 /// 将对象转换为日期时间类型 311 /// </summary> 312 /// <param name="obj">要转换的对象</param> 313 /// <param name="defValue">缺省值</param> 314 /// <returns>转换后的int类型结果</returns> 315 public static DateTime ObjectToDateTime(object obj, DateTime defValue) 316 { 317 return StrToDateTime(obj.ToString(), defValue); 318 } 319 320 /// <summary> 321 /// 将对象转换为字符串 322 /// </summary> 323 /// <param name="obj">要转换的对象</param> 324 /// <returns>转换后的string类型结果</returns> 325 public static string ObjectToStr(object obj) 326 { 327 if (obj == null) 328 return ""; 329 return obj.ToString().Trim(); 330 } 331 #endregion 332 333 #region 分割字符串 334 /// <summary> 335 /// 分割字符串 336 /// </summary> 337 public static string[] SplitString(string strContent, string strSplit) 338 { 339 if (!string.IsNullOrEmpty(strContent)) 340 { 341 if (strContent.IndexOf(strSplit) < 0) 342 return new string[] { strContent }; 343 344 return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase); 345 } 346 else 347 return new string[0] { }; 348 } 349 350 /// <summary> 351 /// 分割字符串 352 /// </summary> 353 /// <returns></returns> 354 public static string[] SplitString(string strContent, string strSplit, int count) 355 { 356 string[] result = new string[count]; 357 string[] splited = SplitString(strContent, strSplit); 358 359 for (int i = 0; i < count; i++) 360 { 361 if (i < splited.Length) 362 result[i] = splited[i]; 363 else 364 result[i] = string.Empty; 365 } 366 367 return result; 368 } 369 #endregion 370 371 #region 删除最后结尾的一个逗号 372 /// <summary> 373 /// 删除最后结尾的一个逗号 374 /// </summary> 375 public static string DelLastComma(string str) 376 { 377 if (str.Length < 1) 378 { 379 return ""; 380 } 381 return str.Substring(0, str.LastIndexOf(",")); 382 } 383 #endregion 384 385 #region 删除最后结尾的指定字符后的字符 386 /// <summary> 387 /// 删除最后结尾的指定字符后的字符 388 /// </summary> 389 public static string DelLastChar(string str, string strchar) 390 { 391 if (string.IsNullOrEmpty(str)) 392 return ""; 393 if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1) 394 { 395 return str.Substring(0, str.LastIndexOf(strchar)); 396 } 397 return str; 398 } 399 #endregion 400 401 #region 生成指定长度的字符串 402 /// <summary> 403 /// 生成指定长度的字符串,即生成strLong个str字符串 404 /// </summary> 405 /// <param name="strLong">生成的长度</param> 406 /// <param name="str">以str生成字符串</param> 407 /// <returns></returns> 408 public static string StringOfChar(int strLong, string str) 409 { 410 string ReturnStr = ""; 411 for (int i = 0; i < strLong; i++) 412 { 413 ReturnStr += str; 414 } 415 416 return ReturnStr; 417 } 418 #endregion 419 420 #region 生成日期随机码 421 /// <summary> 422 /// 生成日期随机码 423 /// </summary> 424 /// <returns></returns> 425 public static string GetRamCode() 426 { 427 #region 428 return DateTime.Now.ToString("yyyyMMddHHmmssffff"); 429 #endregion 430 } 431 #endregion 432 433 #region 生成随机字母或数字 434 /// <summary> 435 /// 生成随机数字 436 /// </summary> 437 /// <param name="length">生成长度</param> 438 /// <returns></returns> 439 public static string Number(int Length) 440 { 441 return Number(Length, false); 442 } 443 444 /// <summary> 445 /// 生成随机数字 446 /// </summary> 447 /// <param name="Length">生成长度</param> 448 /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param> 449 /// <returns></returns> 450 public static string Number(int Length, bool Sleep) 451 { 452 if (Sleep) 453 System.Threading.Thread.Sleep(3); 454 string result = ""; 455 System.Random random = new Random(); 456 for (int i = 0; i < Length; i++) 457 { 458 result += random.Next(10).ToString(); 459 } 460 return result; 461 } 462 /// <summary> 463 /// 生成随机字母字符串(数字字母混和) 464 /// </summary> 465 /// <param name="codeCount">待生成的位数</param> 466 public static string GetCheckCode(int codeCount) 467 { 468 string str = string.Empty; 469 int rep = 0; 470 long num2 = DateTime.Now.Ticks + rep; 471 rep++; 472 Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep))); 473 for (int i = 0; i < codeCount; i++) 474 { 475 char ch; 476 int num = random.Next(); 477 if ((num % 2) == 0) 478 { 479 ch = (char)(0x30 + ((ushort)(num % 10))); 480 } 481 else 482 { 483 ch = (char)(0x41 + ((ushort)(num % 0x1a))); 484 } 485 str = str + ch.ToString(); 486 } 487 return str; 488 } 489 /// <summary> 490 /// 根据日期和随机码生成订单号 491 /// </summary> 492 /// <returns></returns> 493 public static string GetOrderNumber() 494 { 495 string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms 496 return num + Number(2).ToString(); 497 } 498 private static int Next(int numSeeds, int length) 499 { 500 byte[] buffer = new byte[length]; 501 System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider(); 502 Gen.GetBytes(buffer); 503 uint randomResult = 0x0;//这里用uint作为生成的随机数 504 for (int i = 0; i < length; i++) 505 { 506 randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8)); 507 } 508 return (int)(randomResult % numSeeds); 509 } 510 #endregion 511 512 #region 截取字符长度 513 /// <summary> 514 /// 截取字符长度 515 /// </summary> 516 /// <param name="inputString">字符</param> 517 /// <param name="len">长度</param> 518 /// <returns></returns> 519 public static string CutString(string inputString, int len) 520 { 521 if (string.IsNullOrEmpty(inputString)) 522 return ""; 523 inputString = DropHTML(inputString); 524 ASCIIEncoding ascii = new ASCIIEncoding(); 525 int tempLen = 0; 526 string tempString = ""; 527 byte[] s = ascii.GetBytes(inputString); 528 for (int i = 0; i < s.Length; i++) 529 { 530 if ((int)s[i] == 63) 531 { 532 tempLen += 2; 533 } 534 else 535 { 536 tempLen += 1; 537 } 538 539 try 540 { 541 tempString += inputString.Substring(i, 1); 542 } 543 catch 544 { 545 break; 546 } 547 548 if (tempLen > len) 549 break; 550 } 551 //如果截过则加上半个省略号 552 byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); 553 if (mybyte.Length > len) 554 tempString += "…"; 555 return tempString; 556 } 557 #endregion 558 559 #region 清除HTML标记 560 public static string DropHTML(string Htmlstring) 561 { 562 if (string.IsNullOrEmpty(Htmlstring)) return ""; 563 //删除脚本 564 Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase); 565 //删除HTML 566 Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); 567 Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase); 568 Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase); 569 Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); 570 Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase); 571 Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase); 572 Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase); 573 Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase); 574 Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase); 575 Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase); 576 Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase); 577 Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase); 578 Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase); 579 580 Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase); 581 Htmlstring.Replace("<", ""); 582 Htmlstring.Replace(">", ""); 583 Htmlstring.Replace("\r\n", ""); 584 Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim(); 585 return Htmlstring; 586 } 587 #endregion 588 589 #region 清除HTML标记且返回相应的长度 590 public static string DropHTML(string Htmlstring, int strLen) 591 { 592 return CutString(DropHTML(Htmlstring), strLen); 593 } 594 #endregion 595 596 #region TXT代码转换成HTML格式 597 /// <summary> 598 /// 字符串字符处理 599 /// </summary> 600 /// <param name="chr">等待处理的字符串</param> 601 /// <returns>处理后的字符串</returns> 602 /// //把TXT代码转换成HTML格式 603 public static String ToHtml(string Input) 604 { 605 StringBuilder sb = new StringBuilder(Input); 606 sb.Replace("&", "&"); 607 sb.Replace("<", "<"); 608 sb.Replace(">", ">"); 609 sb.Replace("\r\n", "<br />"); 610 sb.Replace("\n", "<br />"); 611 sb.Replace("\t", " "); 612 //sb.Replace(" ", " "); 613 return sb.ToString(); 614 } 615 #endregion 616 617 #region HTML代码转换成TXT格式 618 /// <summary> 619 /// 字符串字符处理 620 /// </summary> 621 /// <param name="chr">等待处理的字符串</param> 622 /// <returns>处理后的字符串</returns> 623 /// //把HTML代码转换成TXT格式 624 public static String ToTxt(String Input) 625 { 626 StringBuilder sb = new StringBuilder(Input); 627 sb.Replace(" ", " "); 628 sb.Replace("<br>", "\r\n"); 629 sb.Replace("<br>", "\n"); 630 sb.Replace("<br />", "\n"); 631 sb.Replace("<br />", "\r\n"); 632 sb.Replace("<", "<"); 633 sb.Replace(">", ">"); 634 sb.Replace("&", "&"); 635 return sb.ToString(); 636 } 637 #endregion 638 639 #region 检测是否有Sql危险字符 640 /// <summary> 641 /// 检测是否有Sql危险字符 642 /// </summary> 643 /// <param name="str">要判断字符串</param> 644 /// <returns>判断结果</returns> 645 public static bool IsSafeSqlString(string str) 646 { 647 return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); 648 } 649 650 /// <summary> 651 /// 检查危险字符 652 /// </summary> 653 /// <param name="Input"></param> 654 /// <returns></returns> 655 public static string Filter(string sInput) 656 { 657 if (sInput == null || sInput == "") 658 return null; 659 string sInput1 = sInput.ToLower(); 660 string output = sInput; 661 string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'"; 662 if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success) 663 { 664 throw new Exception("字符串中含有非法字符!"); 665 } 666 else 667 { 668 output = output.Replace("'", "''"); 669 } 670 return output; 671 } 672 673 /// <summary> 674 /// 检查过滤设定的危险字符 675 /// </summary> 676 /// <param name="InText">要过滤的字符串 </param> 677 /// <returns>如果参数存在不安全字符,则返回true </returns> 678 public static bool SqlFilter(string word, string InText) 679 { 680 if (InText == null) 681 return false; 682 foreach (string i in word.Split('|')) 683 { 684 if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1)) 685 { 686 return true; 687 } 688 } 689 return false; 690 } 691 #endregion 692 693 #region 过滤特殊字符 694 /// <summary> 695 /// 过滤特殊字符 696 /// </summary> 697 /// <param name="Input"></param> 698 /// <returns></returns> 699 public static string Htmls(string Input) 700 { 701 if (Input != string.Empty && Input != null) 702 { 703 string ihtml = Input.ToLower(); 704 ihtml = ihtml.Replace("<script", "<script"); 705 ihtml = ihtml.Replace("script>", "script>"); 706 ihtml = ihtml.Replace("<%", "<%"); 707 ihtml = ihtml.Replace("%>", "%>"); 708 ihtml = ihtml.Replace("<$", "<$"); 709 ihtml = ihtml.Replace("$>", "$>"); 710 return ihtml; 711 } 712 else 713 { 714 return string.Empty; 715 } 716 } 717 #endregion 718 719 #region 检查是否为IP地址 720 /// <summary> 721 /// 是否为ip 722 /// </summary> 723 /// <param name="ip"></param> 724 /// <returns></returns> 725 public static bool IsIP(string ip) 726 { 727 return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); 728 } 729 #endregion 730 731 #region 获得配置文件节点XML文件的绝对路径 732 public static string GetXmlMapPath(string xmlName) 733 { 734 return GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString()); 735 } 736 #endregion 737 738 #region 获得当前绝对路径 739 /// <summary> 740 /// 获得当前绝对路径 741 /// </summary> 742 /// <param name="strPath">指定的路径</param> 743 /// <returns>绝对路径</returns> 744 public static string GetMapPath(string strPath) 745 { 746 if (strPath.ToLower().StartsWith("http://")) 747 { 748 return strPath; 749 } 750 if (HttpContext.Current != null) 751 { 752 return HttpContext.Current.Server.MapPath(strPath); 753 } 754 else //非web程序引用 755 { 756 strPath = strPath.Replace("/", "\\"); 757 if (strPath.StartsWith("\\")) 758 { 759 strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\'); 760 } 761 return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); 762 } 763 } 764 #endregion 765 766 #region 文件操作 767 /// <summary> 768 /// 删除单个文件 769 /// </summary> 770 /// <param name="_filepath">文件相对路径</param> 771 public static bool DeleteFile(string _filepath) 772 { 773 if (string.IsNullOrEmpty(_filepath)) 774 { 775 return false; 776 } 777 string fullpath = GetMapPath(_filepath); 778 if (File.Exists(fullpath)) 779 { 780 File.Delete(fullpath); 781 return true; 782 } 783 return false; 784 } 785 786 /// <summary> 787 /// 删除上传的文件(及缩略图) 788 /// </summary> 789 /// <param name="_filepath"></param> 790 public static void DeleteUpFile(string _filepath) 791 { 792 if (string.IsNullOrEmpty(_filepath)) 793 { 794 return; 795 } 796 string fullpath = GetMapPath(_filepath); //原图 797 if (File.Exists(fullpath)) 798 { 799 File.Delete(fullpath); 800 } 801 if (_filepath.LastIndexOf("/") >= 0) 802 { 803 string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1); 804 string fullTPATH = GetMapPath(thumbnailpath); //宿略图 805 if (File.Exists(fullTPATH)) 806 { 807 File.Delete(fullTPATH); 808 } 809 } 810 } 811 812 /// <summary> 813 /// 删除指定文件夹 814 /// </summary> 815 /// <param name="_dirpath">文件相对路径</param> 816 public static bool DeleteDirectory(string _dirpath) 817 { 818 if (string.IsNullOrEmpty(_dirpath)) 819 { 820 return false; 821 } 822 string fullpath = GetMapPath(_dirpath); 823 if (Directory.Exists(fullpath)) 824 { 825 Directory.Delete(fullpath, true); 826 return true; 827 } 828 return false; 829 } 830 831 /// <summary> 832 /// 修改指定文件夹名称 833 /// </summary> 834 /// <param name="old_dirpath">旧相对路径</param> 835 /// <param name="new_dirpath">新相对路径</param> 836 /// <returns>bool</returns> 837 public static bool MoveDirectory(string old_dirpath, string new_dirpath) 838 { 839 if (string.IsNullOrEmpty(old_dirpath)) 840 { 841 return false; 842 } 843 string fulloldpath = GetMapPath(old_dirpath); 844 string fullnewpath = GetMapPath(new_dirpath); 845 if (Directory.Exists(fulloldpath)) 846 { 847 Directory.Move(fulloldpath, fullnewpath); 848 return true; 849 } 850 return false; 851 } 852 853 /// <summary> 854 /// 返回文件大小KB 855 /// </summary> 856 /// <param name="_filepath">文件相对路径</param> 857 /// <returns>int</returns> 858 public static int GetFileSize(string _filepath) 859 { 860 if (string.IsNullOrEmpty(_filepath)) 861 { 862 return 0; 863 } 864 string fullpath = GetMapPath(_filepath); 865 if (File.Exists(fullpath)) 866 { 867 FileInfo fileInfo = new FileInfo(fullpath); 868 return ((int)fileInfo.Length) / 1024; 869 } 870 return 0; 871 } 872 873 /// <summary> 874 /// 返回文件扩展名,不含“.” 875 /// </summary> 876 /// <param name="_filepath">文件全名称</param> 877 /// <returns>string</returns> 878 public static string GetFileExt(string _filepath) 879 { 880 if (string.IsNullOrEmpty(_filepath)) 881 { 882 return ""; 883 } 884 if (_filepath.LastIndexOf(".") > 0) 885 { 886 return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.” 887 } 888 return ""; 889 } 890 891 /// <summary> 892 /// 返回文件名,不含路径 893 /// </summary> 894 /// <param name="_filepath">文件相对路径</param> 895 /// <returns>string</returns> 896 public static string GetFileName(string _filepath) 897 { 898 return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1); 899 } 900 901 /// <summary> 902 /// 文件是否存在 903 /// </summary> 904 /// <param name="_filepath">文件相对路径</param> 905 /// <returns>bool</returns> 906 public static bool FileExists(string _filepath) 907 { 908 string fullpath = GetMapPath(_filepath); 909 if (File.Exists(fullpath)) 910 { 911 return true; 912 } 913 return false; 914 } 915 #endregion 916 917 #region 读取或写入cookie 918 /// <summary> 919 /// 写cookie值 920 /// </summary> 921 /// <param name="strName">名称</param> 922 /// <param name="strValue">值</param> 923 public static void WriteCookie(string strName, string strValue) 924 { 925 HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; 926 if (cookie == null) 927 { 928 cookie = new HttpCookie(strName); 929 } 930 cookie.Value = UrlEncode(strValue); 931 HttpContext.Current.Response.AppendCookie(cookie); 932 } 933 934 /// <summary> 935 /// 写cookie值 936 /// </summary> 937 /// <param name="strName">名称</param> 938 /// <param name="strValue">值</param> 939 public static void WriteCookie(string strName, string key, string strValue) 940 { 941 HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; 942 if (cookie == null) 943 { 944 cookie = new HttpCookie(strName); 945 } 946 cookie[key] = UrlEncode(strValue); 947 HttpContext.Current.Response.AppendCookie(cookie); 948 } 949 950 /// <summary> 951 /// 写cookie值 952 /// </summary> 953 /// <param name="strName">名称</param> 954 /// <param name="strValue">值</param> 955 public static void WriteCookie(string strName, string key, string strValue, int expires) 956 { 957 HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; 958 if (cookie == null) 959 { 960 cookie = new HttpCookie(strName); 961 } 962 cookie[key] = UrlEncode(strValue); 963 cookie.Expires = DateTime.Now.AddMinutes(expires); 964 HttpContext.Current.Response.AppendCookie(cookie); 965 } 966 967 /// <summary> 968 /// 写cookie值 969 /// </summary> 970 /// <param name="strName">名称</param> 971 /// <param name="strValue">值</param> 972 /// <param name="strValue">过期时间(天数)</param> 973 public static void WriteCookie(string strName, string strValue, int expires) 974 { 975 HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; 976 if (cookie == null) 977 { 978 cookie = new HttpCookie(strName); 979 } 980 cookie.Value = UrlEncode(strValue); 981 //cookie.Expires = DateTime.Now.AddMinutes(expires); 982 cookie.Expires = DateTime.Now.AddDays(expires); 983 HttpContext.Current.Response.AppendCookie(cookie); 984 } 985 986 /// <summary> 987 /// 读cookie值 988 /// </summary> 989 /// <param name="strName">名称</param> 990 /// <returns>cookie值</returns> 991 public static string GetCookie(string strName) 992 { 993 if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null) 994 return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString()); 995 return ""; 996 } 997 998 /// <summary> 999 /// 读cookie值 1000 /// </summary> 1001 /// <param name="strName">名称</param> 1002 /// <returns>cookie值</returns> 1003 public static string GetCookie(string strName, string key) 1004 { 1005 if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null) 1006 return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString()); 1007 1008 return ""; 1009 } 1010 #endregion 1011 1012 #region 替换指定的字符串 1013 /// <summary> 1014 /// 替换指定的字符串 1015 /// </summary> 1016 /// <param name="originalStr">原字符串</param> 1017 /// <param name="oldStr">旧字符串</param> 1018 /// <param name="newStr">新字符串</param> 1019 /// <returns></returns> 1020 public static string ReplaceStr(string originalStr, string oldStr, string newStr) 1021 { 1022 if (string.IsNullOrEmpty(oldStr)) 1023 { 1024 return ""; 1025 } 1026 return originalStr.Replace(oldStr, newStr); 1027 } 1028 #endregion 1029 1030 #region 显示分页 1031 /// <summary> 1032 /// 返回分页页码 1033 /// </summary> 1034 /// <param name="pageSize">页面大小</param> 1035 /// <param name="pageIndex">当前页</param> 1036 /// <param name="totalCount">总记录数</param> 1037 /// <param name="linkUrl">链接地址,__id__代表页码</param> 1038 /// <param name="centSize">中间页码数量</param> 1039 /// <returns></returns> 1040 public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize) 1041 { 1042 //计算页数 1043 if (totalCount < 1 || pageSize < 1) 1044 { 1045 return ""; 1046 } 1047 int pageCount = totalCount / pageSize; 1048 if (pageCount < 1) 1049 { 1050 return ""; 1051 } 1052 if (totalCount % pageSize > 0) 1053 { 1054 pageCount += 1; 1055 } 1056 if (pageCount <= 1) 1057 { 1058 return ""; 1059 } 1060 StringBuilder pageStr = new StringBuilder(); 1061 string pageId = "__id__"; 1062 string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">«上一页</a>"; 1063 string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页»</a>"; 1064 string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>"; 1065 string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>"; 1066 1067 if (pageIndex <= 1) 1068 { 1069 firstBtn = "<span class=\"disabled\">«上一页</span>"; 1070 } 1071 if (pageIndex >= pageCount) 1072 { 1073 lastBtn = "<span class=\"disabled\">下一页»</span>"; 1074 } 1075 if (pageIndex == 1) 1076 { 1077 firstStr = "<span class=\"current\">1</span>"; 1078 } 1079 if (pageIndex == pageCount) 1080 { 1081 lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>"; 1082 } 1083 int firstNum = pageIndex - (centSize / 2); //中间开始的页码 1084 if (pageIndex < centSize) 1085 firstNum = 2; 1086 int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中间结束的页码 1087 if (lastNum >= pageCount) 1088 lastNum = pageCount - 1; 1089 pageStr.Append("<span>共" + totalCount + "记录</span>"); 1090 pageStr.Append(firstBtn + firstStr); 1091 if (pageIndex >= centSize) 1092 { 1093 pageStr.Append("<span>...</span>\n"); 1094 } 1095 for (int i = firstNum; i <= lastNum; i++) 1096 { 1097 if (i == pageIndex) 1098 { 1099 pageStr.Append("<span class=\"current\">" + i + "</span>"); 1100 } 1101 else 1102 { 1103 pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>"); 1104 } 1105 } 1106 if (pageCount - pageIndex > centSize - ((centSize / 2))) 1107 { 1108 pageStr.Append("<span>...</span>"); 1109 } 1110 pageStr.Append(lastStr + lastBtn); 1111 return pageStr.ToString(); 1112 } 1113 #endregion 1114 1115 #region URL处理 1116 /// <summary> 1117 /// URL字符编码 1118 /// </summary> 1119 public static string UrlEncode(string str) 1120 { 1121 if (string.IsNullOrEmpty(str)) 1122 { 1123 return ""; 1124 } 1125 str = str.Replace("'", ""); 1126 return HttpContext.Current.Server.UrlEncode(str); 1127 } 1128 1129 /// <summary> 1130 /// URL字符解码 1131 /// </summary> 1132 public static string UrlDecode(string str) 1133 { 1134 if (string.IsNullOrEmpty(str)) 1135 { 1136 return ""; 1137 } 1138 return HttpContext.Current.Server.UrlDecode(str); 1139 } 1140 1141 /// <summary> 1142 /// 组合URL参数 1143 /// </summary> 1144 /// <param name="_url">页面地址</param> 1145 /// <param name="_keys">参数名称</param> 1146 /// <param name="_values">参数值</param> 1147 /// <returns>String</returns> 1148 public static string CombUrlTxt(string _url, string _keys, params string[] _values) 1149 { 1150 StringBuilder urlParams = new StringBuilder(); 1151 try 1152 { 1153 string[] keyArr = _keys.Split(new char[] { '&' }); 1154 for (int i = 0; i < keyArr.Length; i++) 1155 { 1156 if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0") 1157 { 1158 _values[i] = UrlEncode(_values[i]); 1159 urlParams.Append(string.Format(keyArr[i], _values) + "&"); 1160 } 1161 } 1162 if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1) 1163 urlParams.Insert(0, "?"); 1164 } 1165 catch 1166 { 1167 return _url; 1168 } 1169 return _url + DelLastChar(urlParams.ToString(), "&"); 1170 } 1171 #endregion 1172 1173 #region URL请求数据 1174 /// <summary> 1175 /// HTTP POST方式请求数据 1176 /// </summary> 1177 /// <param name="url">URL.</param> 1178 /// <param name="param">POST的数据</param> 1179 /// <returns></returns> 1180 public static string HttpPost(string url, string param) 1181 { 1182 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 1183 request.Method = "POST"; 1184 request.ContentType = "application/x-www-form-urlencoded"; 1185 request.Accept = "*/*"; 1186 request.Timeout = 15000; 1187 request.AllowAutoRedirect = false; 1188 1189 StreamWriter requestStream = null; 1190 WebResponse response = null; 1191 string responseStr = null; 1192 1193 try 1194 { 1195 requestStream = new StreamWriter(request.GetRequestStream()); 1196 requestStream.Write(param); 1197 requestStream.Close(); 1198 1199 response = request.GetResponse(); 1200 if (response != null) 1201 { 1202 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 1203 responseStr = reader.ReadToEnd(); 1204 reader.Close(); 1205 } 1206 } 1207 catch (Exception) 1208 { 1209 throw; 1210 } 1211 finally 1212 { 1213 request = null; 1214 requestStream = null; 1215 response = null; 1216 } 1217 1218 return responseStr; 1219 } 1220 1221 /// <summary> 1222 /// HTTP GET方式请求数据. 1223 /// </summary> 1224 /// <param name="url">URL.</param> 1225 /// <returns></returns> 1226 public static string HttpGet(string url) 1227 { 1228 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 1229 request.Method = "GET"; 1230 //request.ContentType = "application/x-www-form-urlencoded"; 1231 request.Accept = "*/*"; 1232 request.Timeout = 15000; 1233 request.AllowAutoRedirect = false; 1234 1235 WebResponse response = null; 1236 string responseStr = null; 1237 1238 try 1239 { 1240 response = request.GetResponse(); 1241 1242 if (response != null) 1243 { 1244 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 1245 responseStr = reader.ReadToEnd(); 1246 reader.Close(); 1247 } 1248 } 1249 catch (Exception) 1250 { 1251 throw; 1252 } 1253 finally 1254 { 1255 request = null; 1256 response = null; 1257 } 1258 1259 return responseStr; 1260 } 1261 1262 /// <summary> 1263 /// 执行URL获取页面内容 1264 /// </summary> 1265 public static string UrlExecute(string urlPath) 1266 { 1267 if (string.IsNullOrEmpty(urlPath)) 1268 { 1269 return "error"; 1270 } 1271 StringWriter sw = new StringWriter(); 1272 try 1273 { 1274 HttpContext.Current.Server.Execute(urlPath, sw); 1275 return sw.ToString(); 1276 } 1277 catch (Exception) 1278 { 1279 return "error"; 1280 } 1281 finally 1282 { 1283 sw.Close(); 1284 sw.Dispose(); 1285 } 1286 } 1287 #endregion 1288 1289 #region 操作权限菜单 1290 /// <summary> 1291 /// 获取操作权限 1292 /// </summary> 1293 /// <returns>Dictionary</returns> 1294 public static Dictionary<string, string> ActionType() 1295 { 1296 Dictionary<string, string> dic = new Dictionary<string, string>(); 1297 dic.Add("Show", "显示"); 1298 dic.Add("View", "查看"); 1299 dic.Add("Add", "添加"); 1300 dic.Add("Edit", "修改"); 1301 dic.Add("Delete", "删除"); 1302 dic.Add("Audit", "审核"); 1303 dic.Add("Reply", "回复"); 1304 dic.Add("Confirm", "确认"); 1305 dic.Add("Cancel", "取消"); 1306 dic.Add("Invalid", "作废"); 1307 dic.Add("Build", "生成"); 1308 dic.Add("Instal", "安装"); 1309 dic.Add("Unload", "卸载"); 1310 dic.Add("Back", "备份"); 1311 dic.Add("Restore", "还原"); 1312 dic.Add("Replace", "替换"); 1313 return dic; 1314 } 1315 #endregion 1316 1317 #region 替换URL 1318 /// <summary> 1319 /// 替换扩展名 1320 /// </summary> 1321 public static string GetUrlExtension(string urlPage, string staticExtension) 1322 { 1323 int indexNum = urlPage.LastIndexOf('.'); 1324 if (indexNum > 0) 1325 { 1326 return urlPage.Replace(urlPage.Substring(indexNum), "." + staticExtension); 1327 } 1328 return urlPage; 1329 } 1330 /// <summary> 1331 /// 替换扩展名,如没有扩展名替换默认首页 1332 /// </summary> 1333 public static string GetUrlExtension(string urlPage, string staticExtension, bool defaultVal) 1334 { 1335 int indexNum = urlPage.LastIndexOf('.'); 1336 if (indexNum > 0) 1337 { 1338 return urlPage.Replace(urlPage.Substring(indexNum), "." + staticExtension); 1339 } 1340 if (defaultVal) 1341 { 1342 if (urlPage.EndsWith("/")) 1343 { 1344 return urlPage + "index." + staticExtension; 1345 } 1346 else 1347 { 1348 return urlPage + "/index." + staticExtension; 1349 } 1350 } 1351 return urlPage; 1352 } 1353 #endregion 1354 1355 1356 #region 写入图片流 1357 /// <summary> 1358 /// 读取图片流 1359 /// </summary> 1360 /// <param name="fileUrl">图片路径</param> 1361 /// <returns></returns> 1362 public static byte[] writeByte(string fileUrl) 1363 { 1364 byte[] buffer = null; 1365 using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read)) 1366 { 1367 using (BinaryReader br = new BinaryReader(fs)) 1368 { 1369 buffer = br.ReadBytes(Convert.ToInt32(fs.Length)); 1370 } 1371 1372 } 1373 return buffer; 1374 } 1375 #endregion 1376 1377 #region 读取图片流 1378 /// <summary> 1379 /// 读取图片流 1380 /// </summary> 1381 /// <param name="fileUrl">图片路径</param> 1382 /// <returns></returns> 1383 //public static void ReadByte(byte[] buffer) 1384 //{ 1385 // using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read)) 1386 // { 1387 // using (BinaryWriter br = new BinaryWriter(fs)) 1388 // { 1389 // br.Write(buffer); 1390 // } 1391 // } 1392 //} 1393 #endregion 1394 #region 删除图片 1395 /// <summary> 1396 /// 删除图片 1397 /// </summary> 1398 /// <param name="fileUrl">图片路径</param> 1399 public static void delteImg(string fileUrl) 1400 { 1401 if (!string.IsNullOrEmpty(fileUrl)) 1402 File.Delete(fileUrl); 1403 } 1404 #endregion 1405 1406 1407 public static object FromDbValue(object value) 1408 { 1409 if (value == DBNull.Value) 1410 { 1411 return null; 1412 } 1413 else 1414 { 1415 return value; 1416 } 1417 } 1418 1419 /// <summary> 1420 /// 插入数据库。C#中的null值转为sql中的null 1421 /// </summary> 1422 /// <param name="value"></param> 1423 /// <returns></returns> 1424 public static object ToDbValue(object value) 1425 { 1426 if (value == null) 1427 { 1428 return DBNull.Value; 1429 } 1430 else 1431 { 1432 return value; 1433 } 1434 } 1435 1436 1437 1438 1439 /// <summary> 1440 /// 逻辑类型转换 1441 /// </summary> 1442 /// <param name="sValue">传递需要转换的字符参数</param> 1443 /// <returns>将指定的参数转换成bool类型值返回</returns> 1444 public static bool GetBooleanValue(string sValue) 1445 { 1446 return GetBooleanValue(sValue, false); 1447 } 1448 1449 /// <summary> 1450 /// 逻辑类型转换 1451 /// </summary> 1452 /// <param name="oValue">传递需要转换的对象参数</param> 1453 /// <returns>将指定的参数转换成bool类型值返回</returns> 1454 public static bool GetBooleanValue(object oValue) 1455 { 1456 return GetBooleanValue(oValue.ToString(), false); 1457 } 1458 1459 /// <summary> 1460 /// 逻辑类型转换 1461 /// </summary> 1462 /// <param name="sValue">传递需要转换的字符参数</param> 1463 /// <param name="bDefault">默认值</param> 1464 /// <returns>将指定的参数转换成bool类型值返回,如果异常则返回默认值</returns> 1465 public static bool GetBooleanValue(string sValue, bool bDefault) 1466 { 1467 if (((sValue != null) && (sValue != ""))) 1468 { 1469 bool b; 1470 if (bool.TryParse(sValue, out b)) 1471 { 1472 return b; 1473 } 1474 else 1475 { 1476 return bDefault; 1477 } 1478 } 1479 else 1480 { 1481 return bDefault; 1482 } 1483 } 1484 1485 1486 /// <summary> 1487 /// 日期转换,如转换失败返回当天日期 1488 /// </summary> 1489 /// <param name="sValue">传递需要转换的字符参数</param> 1490 /// <returns>将传递的参数转换成日期类型返回,如转换失败返回默认日期</returns> 1491 public static DateTime GetDateTimeValue(string sValue) 1492 { 1493 return GetDateTimeValue(sValue, DateTime.Now); 1494 } 1495 1496 /// <summary> 1497 /// 日期转换,如转换失败返回当天日期 1498 /// </summary> 1499 /// <param name="oValue">传递需要转换的对象参数</param> 1500 /// <returns>将传递的参数转换成日期类型返回,如转换失败返回默认日期</returns> 1501 public static DateTime GetDateTimeValue(object oValue) 1502 { 1503 return GetDateTimeValue(oValue.ToString(), DateTime.Now); 1504 } 1505 1506 /// <summary> 1507 /// 日期转换,如转换失败返回默认日期 1508 /// </summary> 1509 /// <param name="sValue">需要转换的字符串</param> 1510 /// <param name="dDefault">默认值</param> 1511 /// <returns>将传递的参数转换成日期类型返回,如转换失败返回默认日期</returns> 1512 public static DateTime GetDateTimeValue(string sValue, DateTime dDefault) 1513 { 1514 if (((sValue != null) && (sValue != ""))) 1515 { 1516 DateTime t; 1517 if (DateTime.TryParse(sValue, out t)) 1518 { 1519 return t; 1520 } 1521 else 1522 { 1523 return dDefault; 1524 } 1525 } 1526 else 1527 { 1528 return dDefault; 1529 } 1530 } 1531 1532 /// <summary> 1533 /// float类型转换,如转换失败返回0 1534 /// </summary> 1535 /// <param name="sValue">需要转换的字符串</param> 1536 /// <returns>将传递的参数转换成浮点类型,如果转换失败返回0</returns> 1537 public static float GetFloatValue(string sValue) 1538 { 1539 return GetFloatValue(sValue, .0f); 1540 } 1541 1542 /// <summary> 1543 /// float类型转换,如转换失败返回0 1544 /// </summary> 1545 /// <param name="oValue">需要转换的对象</param> 1546 /// <returns>将传递的参数转换成浮点类型,如果转换失败返回0</returns> 1547 public static float GetFloatValue(object oValue) 1548 { 1549 return GetFloatValue(oValue.ToString(), .0f); 1550 } 1551 1552 /// <summary> 1553 /// float类型转换,如转换失败返回默认值 1554 /// </summary> 1555 /// <param name="oValue">需要转换的对象</param> 1556 /// <param name="fValue">默认值</param> 1557 /// <returns>将传递的参数转换成浮点类型,如果转换失败返回0</returns> 1558 public static float GetFloatValue(object oValue, float fValue) 1559 { 1560 return GetFloatValue(oValue.ToString(), fValue); 1561 } 1562 1563 /// <summary> 1564 /// float类型转换,如转换失败返回默认值 1565 /// </summary> 1566 /// <param name="sValue">需要转换的字符串</param> 1567 /// <param name="fValue">默认值</param> 1568 /// <returns>将传递的参数转换成浮点类型,如果转换失败返回0</returns> 1569 public static float GetFloatValue(string sValue, float fValue) 1570 { 1571 float iValue = 0f; 1572 1573 if (!float.TryParse(sValue, out iValue)) 1574 { 1575 iValue = fValue; 1576 } 1577 1578 return iValue; 1579 } 1580 1581 1582 1583 /// <summary> 1584 /// Int32类型转换,如转换失败返回0 1585 /// </summary> 1586 /// <param name="sValue">需要转换的字符串</param> 1587 /// <returns>将传递的参数转换成整形,如果转换失败返回0</returns> 1588 public static int GetIntValue(string sValue) 1589 { 1590 if (string.IsNullOrEmpty(sValue)) return 0; 1591 1592 return GetIntValue(sValue, 0); 1593 } 1594 1595 /// <summary> 1596 /// Int32类型转换,如转换失败返回0 1597 /// </summary> 1598 /// <param name="oValue">需要转换的对象</param> 1599 /// <returns>将传递的参数转换成整形,如果转换失败返回0</returns> 1600 public static int GetIntValue(object oValue) 1601 { 1602 //if (oValue == null) return 0; 1603 return GetIntValue(oValue.ToString(), 0); 1604 } 1605 1606 /// <summary> 1607 /// Int32类型转换,如转换失败返回默认值 1608 /// </summary> 1609 /// <param name="sValue">需要转换的字符串</param> 1610 /// <param name="iDefault">默认值</param> 1611 /// <returns>将传递的参数转换成整形,如果转换失败返回指定的默认值</returns> 1612 public static int GetIntValue(string sValue, int iDefault) 1613 { 1614 int iValue = 0; 1615 //if (((sValue != null) && (sValue != "")) && ValidateUtils.IsNumeric(sValue)) 1616 //{ 1617 1618 // iValue = Convert.ToInt32(sValue); 1619 //} 1620 //else 1621 //{ 1622 // iValue = iDefault; 1623 //} 1624 1625 if (string.IsNullOrEmpty(sValue)) return iDefault; 1626 1627 1628 if (!int.TryParse(sValue, out iValue)) 1629 { 1630 iValue = iDefault; 1631 } 1632 1633 return iValue; 1634 } 1635 1636 /// <summary> 1637 /// long类型转换,如转换失败返回默认值 1638 /// </summary> 1639 /// <param name="sValue">需要转换的字符串</param> 1640 /// <param name="iDefault">64默认值</param> 1641 /// <returns>将传递的参数转换成长整形,如果转换失败返回指定的默认值</returns> 1642 public static long GetlongValue(string sValue, Int64 iDefault) 1643 { 1644 long iValue = 0; 1645 //if (((sValue != null) && (sValue != "")) && ValidateUtils.IsNumeric(sValue)) 1646 //{ 1647 1648 // iValue = Convert.ToInt32(sValue); 1649 //} 1650 //else 1651 //{ 1652 // iValue = iDefault; 1653 //} 1654 1655 if (string.IsNullOrEmpty(sValue)) return iDefault; 1656 1657 1658 if (!long.TryParse(sValue, out iValue)) 1659 { 1660 iValue = iDefault; 1661 } 1662 1663 return iValue; 1664 } 1665 1666 /// <summary> 1667 /// Int32类型转换,如转换失败返回默认值 1668 /// </summary> 1669 /// <param name="oValue">需要转换的对象</param> 1670 /// <param name="iDefault">默认值</param> 1671 /// <returns>将传递的参数转换成整形,如果转换失败返回指定的默认值</returns> 1672 public static int GetIntValue(object oValue, int iDefault) 1673 { 1674 int iValue = 0; 1675 //if (((sValue != null) && (sValue != "")) && ValidateUtils.IsNumeric(sValue)) 1676 //{ 1677 1678 // iValue = Convert.ToInt32(sValue); 1679 //} 1680 //else 1681 //{ 1682 // iValue = iDefault; 1683 //} 1684 1685 if (oValue == null) return iDefault; 1686 1687 if (!int.TryParse(oValue.ToString(), out iValue)) 1688 { 1689 iValue = iDefault; 1690 } 1691 1692 return iValue; 1693 } 1694 1695 /// <summary> 1696 /// 得到字符串记录 1697 /// </summary> 1698 /// <param name="oValue">需要转换的对象</param> 1699 /// <returns>将传递的参数转换成字符类型返回,如果传递的参数为空则返回""</returns> 1700 public static string GetStringValue(object oValue) 1701 { 1702 return GetStringValue(oValue, ""); 1703 } 1704 1705 /// <summary> 1706 /// 得到字符串记录 1707 /// </summary> 1708 /// <param name="oValue">需要转换的对象</param> 1709 /// <returns>将传递的参数转换成字符类型返回,如果传递的参数为空则返回""</returns> 1710 public static string GetStringValue(object oValue, string sDefaultValue) 1711 { 1712 if (oValue == null) 1713 return sDefaultValue; 1714 else 1715 return oValue.ToString().Trim(); 1716 } 1717 1718 ///// <summary> 1719 ///// 得到字符串记录 1720 ///// </summary> 1721 ///// <param name="sValue">需要转换的字符串</param> 1722 ///// <returns>将传递的参数转换成字符类型返回,如果传递的参数为空则返回""</returns> 1723 //public static string GetStringValue(string sValue) 1724 //{ 1725 // if (string.IsNullOrEmpty(sValue)) 1726 // return ""; 1727 // else 1728 // return sValue.Trim(); 1729 //} 1730 1731 1732 1733 /// <summary> 1734 /// decimal类型转换,如转换失败返回0 1735 /// </summary> 1736 /// <param name="sValue">需要转换的字符串</param> 1737 /// <returns>返回decimal类型,,如转换失败返回0</returns> 1738 public static decimal GetDecimalValue(string sValue) 1739 { 1740 return GetDecimalValue(sValue, 0, 4); 1741 } 1742 1743 /// <summary> 1744 /// decimal类型转换,如转换失败返回0 1745 /// </summary> 1746 /// <param name="oValue">需要转换的对象</param> 1747 /// <returns>f返回decimal类型,,如转换失败返回0</returns> 1748 public static decimal GetDecimalValue(object oValue) 1749 { 1750 return GetDecimalValue(oValue.ToString(), 0, 4); 1751 } 1752 1753 /// <summary> 1754 /// decimal类型转换,如转换失败返回默认值 1755 /// </summary> 1756 /// <param name="oValue">需要转换的字符串</param> 1757 /// <param name="fValue">默认值</param> 1758 /// <returns>返回decimal类型,,如转换失败返回指定的默认值</returns> 1759 public static decimal GetDecimalValue(object oValue, decimal fValue) 1760 { 1761 return GetDecimalValue(oValue.ToString(), fValue, 4); 1762 } 1763 1764 /// <summary> 1765 /// decimal类型转换,如转换失败返回默认值 1766 /// </summary> 1767 /// <param name="sValue">需要转换的字符串</param> 1768 /// <param name="fValue">默认值</param> 1769 /// <returns>返回decimal类型,,如转换失败返回指定的默认值</returns> 1770 public static decimal GetDecimalValue(string sValue, decimal fValue) 1771 { 1772 return GetDecimalValue(sValue, fValue, 4); 1773 } 1774 1775 /// <summary> 1776 /// decimal类型转换,如转换失败返回默认值 1777 /// </summary> 1778 /// <param name="sValue">需要转换的字符串</param> 1779 /// <param name="fValue">默认值</param> 1780 /// <param name="iPointNum">小数位数</param> 1781 /// <returns>返回decimal类型,,如转换失败返回指定的默认值</returns> 1782 public static decimal GetDecimalValue(string sValue, decimal fValue, int iPointNum) 1783 { 1784 decimal iValue = 0; 1785 1786 if (!decimal.TryParse(sValue, out iValue)) 1787 { 1788 iValue = fValue; 1789 } 1790 1791 return Math.Round(iValue, iPointNum); 1792 } 1793 1794 } 1795 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?