商城手机版

Utils.cs 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using System.IO;
  6. using System.Net;
  7. using System.Configuration;
  8. using System.Web;
  9. using System.Security.Cryptography;
  10. namespace ShopMobile.Common
  11. {
  12. public class Utils
  13. {
  14. #region 系统版本
  15. /// <summary>
  16. /// 版本信息类
  17. /// </summary>
  18. public class VersionInfo
  19. {
  20. public int FileMajorPart
  21. {
  22. get { return 3; }
  23. }
  24. public int FileMinorPart
  25. {
  26. get { return 0; }
  27. }
  28. public int FileBuildPart
  29. {
  30. get { return 7; }
  31. }
  32. public string ProductName
  33. {
  34. get { return "ShopMobile"; }
  35. }
  36. public int ProductType
  37. {
  38. get { return 1; }
  39. }
  40. }
  41. #endregion
  42. #region MD5加密
  43. public static string MD5(string pwd)
  44. {
  45. return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
  46. }
  47. #endregion
  48. #region SHA256加密
  49. public static string SHA256(string pwd)
  50. {
  51. //byte[] SHA256Data = Encoding.UTF8.GetBytes(pwd);
  52. //SHA256Managed Sha256 = new SHA256Managed();
  53. //byte[] Result = Sha256.ComputeHash(SHA256Data);
  54. //return Convert.ToBase64String(Result); //返回长度为44字节的字符串
  55. using (SHA256Managed sha256 = new SHA256Managed())
  56. {
  57. var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(pwd));
  58. var sb = new StringBuilder(hash.Length * 2);
  59. foreach (byte b in hash)
  60. {
  61. sb.Append(b.ToString("x2"));
  62. }
  63. return sb.ToString();
  64. }
  65. }
  66. public static string SHA1(string pwd)
  67. {
  68. return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "SHA1");
  69. }
  70. #endregion
  71. #region 对象转换处理
  72. /// <summary>
  73. /// 判断对象是否为Int32类型的数字
  74. /// </summary>
  75. /// <param name="Expression"></param>
  76. /// <returns></returns>
  77. public static bool IsNumeric(object expression)
  78. {
  79. if (expression != null)
  80. return IsNumeric(expression.ToString());
  81. return false;
  82. }
  83. /// <summary>
  84. /// 判断对象是否为Int32类型的数字
  85. /// </summary>
  86. /// <param name="Expression"></param>
  87. /// <returns></returns>
  88. public static bool IsNumeric(string expression)
  89. {
  90. if (expression != null)
  91. {
  92. string str = expression;
  93. if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))
  94. {
  95. if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
  96. return true;
  97. }
  98. }
  99. return false;
  100. }
  101. /// <summary>
  102. /// 是否为Double类型
  103. /// </summary>
  104. /// <param name="expression"></param>
  105. /// <returns></returns>
  106. public static bool IsDouble(object expression)
  107. {
  108. if (expression != null)
  109. return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
  110. return false;
  111. }
  112. /// <summary>
  113. /// 检测是否符合email格式
  114. /// </summary>
  115. /// <param name="strEmail">要判断的email字符串</param>
  116. /// <returns>判断结果</returns>
  117. public static bool IsValidEmail(string strEmail)
  118. {
  119. return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");
  120. }
  121. public static bool IsValidDoEmail(string strEmail)
  122. {
  123. 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})(\]?)$");
  124. }
  125. /// <summary>
  126. /// 检测是否是正确的Url
  127. /// </summary>
  128. /// <param name="strUrl">要验证的Url</param>
  129. /// <returns>判断结果</returns>
  130. public static bool IsURL(string strUrl)
  131. {
  132. 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\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
  133. }
  134. /// <summary>
  135. /// 将字符串转换为数组
  136. /// </summary>
  137. /// <param name="str">字符串</param>
  138. /// <returns>字符串数组</returns>
  139. public static string[] GetStrArray(string str)
  140. {
  141. return str.Split(new char[',']);
  142. }
  143. /// <summary>
  144. /// 将数组转换为字符串
  145. /// </summary>
  146. /// <param name="list">List</param>
  147. /// <param name="speater">分隔符</param>
  148. /// <returns>String</returns>
  149. public static string GetArrayStr(List<string> list, string speater)
  150. {
  151. StringBuilder sb = new StringBuilder();
  152. for (int i = 0; i < list.Count; i++)
  153. {
  154. if (i == list.Count - 1)
  155. {
  156. sb.Append(list[i]);
  157. }
  158. else
  159. {
  160. sb.Append(list[i]);
  161. sb.Append(speater);
  162. }
  163. }
  164. return sb.ToString();
  165. }
  166. /// <summary>
  167. /// object型转换为bool型
  168. /// </summary>
  169. /// <param name="strValue">要转换的字符串</param>
  170. /// <param name="defValue">缺省值</param>
  171. /// <returns>转换后的bool类型结果</returns>
  172. public static bool StrToBool(object expression, bool defValue)
  173. {
  174. if (expression != null)
  175. return StrToBool(expression, defValue);
  176. return defValue;
  177. }
  178. /// <summary>
  179. /// string型转换为bool型
  180. /// </summary>
  181. /// <param name="strValue">要转换的字符串</param>
  182. /// <param name="defValue">缺省值</param>
  183. /// <returns>转换后的bool类型结果</returns>
  184. public static bool StrToBool(string expression, bool defValue)
  185. {
  186. if (expression != null)
  187. {
  188. if (string.Compare(expression, "true", true) == 0)
  189. return true;
  190. else if (string.Compare(expression, "false", true) == 0)
  191. return false;
  192. }
  193. return defValue;
  194. }
  195. /// <summary>
  196. /// 将对象转换为Int32类型
  197. /// </summary>
  198. /// <param name="expression">要转换的字符串</param>
  199. /// <param name="defValue">缺省值</param>
  200. /// <returns>转换后的int类型结果</returns>
  201. public static int ObjToInt(object expression, int defValue)
  202. {
  203. if (expression != null)
  204. return StrToInt(expression.ToString(), defValue);
  205. return defValue;
  206. }
  207. /// <summary>
  208. /// 将字符串转换为Int32类型
  209. /// </summary>
  210. /// <param name="expression">要转换的字符串</param>
  211. /// <param name="defValue">缺省值</param>
  212. /// <returns>转换后的int类型结果</returns>
  213. public static int StrToInt(string expression, int defValue)
  214. {
  215. if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
  216. return defValue;
  217. int rv;
  218. if (Int32.TryParse(expression, out rv))
  219. return rv;
  220. return Convert.ToInt32(StrToFloat(expression, defValue));
  221. }
  222. /// <summary>
  223. /// Object型转换为decimal型
  224. /// </summary>
  225. /// <param name="strValue">要转换的字符串</param>
  226. /// <param name="defValue">缺省值</param>
  227. /// <returns>转换后的decimal类型结果</returns>
  228. public static decimal ObjToDecimal(object expression, decimal defValue)
  229. {
  230. if (expression != null)
  231. return StrToDecimal(expression.ToString(), defValue);
  232. return defValue;
  233. }
  234. /// <summary>
  235. /// string型转换为decimal型
  236. /// </summary>
  237. /// <param name="strValue">要转换的字符串</param>
  238. /// <param name="defValue">缺省值</param>
  239. /// <returns>转换后的decimal类型结果</returns>
  240. public static decimal StrToDecimal(string expression, decimal defValue)
  241. {
  242. if ((expression == null) || (expression.Length > 10))
  243. return defValue;
  244. decimal intValue = defValue;
  245. if (expression != null)
  246. {
  247. bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
  248. if (IsDecimal)
  249. decimal.TryParse(expression, out intValue);
  250. }
  251. return intValue;
  252. }
  253. /// <summary>
  254. /// Object型转换为float型
  255. /// </summary>
  256. /// <param name="strValue">要转换的字符串</param>
  257. /// <param name="defValue">缺省值</param>
  258. /// <returns>转换后的int类型结果</returns>
  259. public static float ObjToFloat(object expression, float defValue)
  260. {
  261. if (expression != null)
  262. return StrToFloat(expression.ToString(), defValue);
  263. return defValue;
  264. }
  265. /// <summary>
  266. /// string型转换为float型
  267. /// </summary>
  268. /// <param name="strValue">要转换的字符串</param>
  269. /// <param name="defValue">缺省值</param>
  270. /// <returns>转换后的int类型结果</returns>
  271. public static float StrToFloat(string expression, float defValue)
  272. {
  273. if ((expression == null) || (expression.Length > 10))
  274. return defValue;
  275. float intValue = defValue;
  276. if (expression != null)
  277. {
  278. bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
  279. if (IsFloat)
  280. float.TryParse(expression, out intValue);
  281. }
  282. return intValue;
  283. }
  284. /// <summary>
  285. /// 将对象转换为日期时间类型
  286. /// </summary>
  287. /// <param name="str">要转换的字符串</param>
  288. /// <param name="defValue">缺省值</param>
  289. /// <returns>转换后的int类型结果</returns>
  290. public static DateTime StrToDateTime(string str, DateTime defValue)
  291. {
  292. if (!string.IsNullOrEmpty(str))
  293. {
  294. DateTime dateTime;
  295. if (DateTime.TryParse(str, out dateTime))
  296. return dateTime;
  297. }
  298. return defValue;
  299. }
  300. /// <summary>
  301. /// 将对象转换为日期时间类型
  302. /// </summary>
  303. /// <param name="str">要转换的字符串</param>
  304. /// <returns>转换后的int类型结果</returns>
  305. public static DateTime StrToDateTime(string str)
  306. {
  307. return StrToDateTime(str, DateTime.Now);
  308. }
  309. /// <summary>
  310. /// 将对象转换为日期时间类型
  311. /// </summary>
  312. /// <param name="obj">要转换的对象</param>
  313. /// <returns>转换后的int类型结果</returns>
  314. public static DateTime ObjectToDateTime(object obj)
  315. {
  316. return StrToDateTime(obj.ToString());
  317. }
  318. /// <summary>
  319. /// 将对象转换为日期时间类型
  320. /// </summary>
  321. /// <param name="obj">要转换的对象</param>
  322. /// <param name="defValue">缺省值</param>
  323. /// <returns>转换后的int类型结果</returns>
  324. public static DateTime ObjectToDateTime(object obj, DateTime defValue)
  325. {
  326. return StrToDateTime(obj.ToString(), defValue);
  327. }
  328. /// <summary>
  329. /// 将对象转换为字符串
  330. /// </summary>
  331. /// <param name="obj">要转换的对象</param>
  332. /// <returns>转换后的string类型结果</returns>
  333. public static string ObjectToStr(object obj)
  334. {
  335. if (obj == null)
  336. return "";
  337. return obj.ToString().Trim();
  338. }
  339. /// <summary>
  340. /// 取该日期的星期几
  341. /// </summary>
  342. /// <param name="dayTimes">日期</param>
  343. /// <returns></returns>
  344. public static string GetDayName(DateTime dayTimes)
  345. {
  346. string result = "";
  347. if (dayTimes.DayOfWeek == DayOfWeek.Monday)
  348. {
  349. result = "星期一";
  350. }
  351. else if (dayTimes.DayOfWeek == DayOfWeek.Tuesday)
  352. {
  353. result = "星期二";
  354. }
  355. else if (dayTimes.DayOfWeek == DayOfWeek.Wednesday)
  356. {
  357. result = "星期三";
  358. }
  359. else if (dayTimes.DayOfWeek == DayOfWeek.Thursday)
  360. {
  361. result = "星期四";
  362. }
  363. else if (dayTimes.DayOfWeek == DayOfWeek.Friday)
  364. {
  365. result = "星期五";
  366. }
  367. else if (dayTimes.DayOfWeek == DayOfWeek.Saturday)
  368. {
  369. result = "星期六";
  370. }
  371. else if (dayTimes.DayOfWeek == DayOfWeek.Sunday)
  372. {
  373. result = "星期日";
  374. }
  375. return result;
  376. }
  377. #endregion
  378. #region 分割字符串
  379. /// <summary>
  380. /// 分割字符串
  381. /// </summary>
  382. public static string[] SplitString(string strContent, string strSplit)
  383. {
  384. if (!string.IsNullOrEmpty(strContent))
  385. {
  386. if (strContent.IndexOf(strSplit) < 0)
  387. return new string[] { strContent };
  388. return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
  389. }
  390. else
  391. return new string[0] { };
  392. }
  393. /// <summary>
  394. /// 分割字符串
  395. /// </summary>
  396. /// <returns></returns>
  397. public static string[] SplitString(string strContent, string strSplit, int count)
  398. {
  399. string[] result = new string[count];
  400. string[] splited = SplitString(strContent, strSplit);
  401. for (int i = 0; i < count; i++)
  402. {
  403. if (i < splited.Length)
  404. result[i] = splited[i];
  405. else
  406. result[i] = string.Empty;
  407. }
  408. return result;
  409. }
  410. #endregion
  411. #region 删除最后结尾的一个逗号
  412. /// <summary>
  413. /// 删除最后结尾的一个逗号
  414. /// </summary>
  415. public static string DelLastComma(string str)
  416. {
  417. if (str.Length < 1)
  418. {
  419. return "";
  420. }
  421. return str.Substring(0, str.LastIndexOf(","));
  422. }
  423. #endregion
  424. #region 删除最后结尾的指定字符后的字符
  425. /// <summary>
  426. /// 删除最后结尾的指定字符后的字符
  427. /// </summary>
  428. public static string DelLastChar(string str, string strchar)
  429. {
  430. if (string.IsNullOrEmpty(str))
  431. return "";
  432. if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)
  433. {
  434. return str.Substring(0, str.LastIndexOf(strchar));
  435. }
  436. return str;
  437. }
  438. #endregion
  439. #region 生成指定长度的字符串
  440. /// <summary>
  441. /// 生成指定长度的字符串,即生成strLong个str字符串
  442. /// </summary>
  443. /// <param name="strLong">生成的长度</param>
  444. /// <param name="str">以str生成字符串</param>
  445. /// <returns></returns>
  446. public static string StringOfChar(int strLong, string str)
  447. {
  448. string ReturnStr = "";
  449. for (int i = 0; i < strLong; i++)
  450. {
  451. ReturnStr += str;
  452. }
  453. return ReturnStr;
  454. }
  455. #endregion
  456. #region 生成日期随机码
  457. /// <summary>
  458. /// 生成日期随机码
  459. /// </summary>
  460. /// <returns></returns>
  461. public static string GetRamCode()
  462. {
  463. #region
  464. return DateTime.Now.ToString("yyyyMMddHHmmssffff");
  465. #endregion
  466. }
  467. #endregion
  468. #region 生成随机字母或数字
  469. /// <summary>
  470. /// 生成随机数字
  471. /// </summary>
  472. /// <param name="length">生成长度</param>
  473. /// <returns></returns>
  474. public static string Number(int Length)
  475. {
  476. return Number(Length, false);
  477. }
  478. /// <summary>
  479. /// 生成随机数字
  480. /// </summary>
  481. /// <param name="Length">生成长度</param>
  482. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  483. /// <returns></returns>
  484. public static string Number(int Length, bool Sleep)
  485. {
  486. if (Sleep)
  487. System.Threading.Thread.Sleep(3);
  488. string result = "";
  489. System.Random random = new Random();
  490. for (int i = 0; i < Length; i++)
  491. {
  492. result += random.Next(10).ToString();
  493. }
  494. return result;
  495. }
  496. /// <summary>
  497. /// 生成随机字母字符串(数字字母混和)
  498. /// </summary>
  499. /// <param name="codeCount">待生成的位数</param>
  500. public static string GetCheckCode(int codeCount)
  501. {
  502. string str = string.Empty;
  503. int rep = 0;
  504. long num2 = DateTime.Now.Ticks + rep;
  505. rep++;
  506. Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
  507. for (int i = 0; i < codeCount; i++)
  508. {
  509. char ch;
  510. int num = random.Next();
  511. if ((num % 2) == 0)
  512. {
  513. ch = (char)(0x30 + ((ushort)(num % 10)));
  514. }
  515. else
  516. {
  517. ch = (char)(0x41 + ((ushort)(num % 0x1a)));
  518. }
  519. str = str + ch.ToString();
  520. }
  521. return str;
  522. }
  523. /// <summary>
  524. /// 生成随机字母和数据字符串(字母和数字混合)
  525. /// author:李朴 datetime:2013-12-4
  526. /// </summary>
  527. /// <param name="Length"></param>
  528. /// <returns></returns>
  529. public static string GetLetterOrNumberRandom(int Length)
  530. {
  531. System.Threading.Thread.Sleep(3);
  532. long tick = DateTime.Now.Ticks;//1个以0.1纳秒为单位的时间戳,18位
  533. char[] constant = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
  534. System.Text.StringBuilder newRandom = new System.Text.StringBuilder(constant.Length);
  535. Random rd = new Random(unchecked((int)tick));
  536. for (int i = 0; i < Length; i++)
  537. {
  538. newRandom.Append(constant[rd.Next(constant.Length)]);
  539. }
  540. return newRandom.ToString();
  541. }
  542. /// <summary>
  543. /// 根据日期和随机码生成订单号
  544. /// </summary>
  545. /// <returns></returns>
  546. public static string GetOrderNumber()
  547. {
  548. string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
  549. return num + Number(2, true).ToString();
  550. }
  551. private static int Next(int numSeeds, int length)
  552. {
  553. byte[] buffer = new byte[length];
  554. System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
  555. Gen.GetBytes(buffer);
  556. uint randomResult = 0x0;//这里用uint作为生成的随机数
  557. for (int i = 0; i < length; i++)
  558. {
  559. randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
  560. }
  561. return (int)(randomResult % numSeeds);
  562. }
  563. #endregion
  564. #region 截取字符长度
  565. /// <summary>
  566. /// 截取字符长度
  567. /// </summary>
  568. /// <param name="inputString">字符</param>
  569. /// <param name="len">长度</param>
  570. /// <returns></returns>
  571. public static string CutString(string inputString, int len)
  572. {
  573. if (string.IsNullOrEmpty(inputString))
  574. return "";
  575. inputString = DropHTML(inputString);
  576. ASCIIEncoding ascii = new ASCIIEncoding();
  577. int tempLen = 0;
  578. string tempString = "";
  579. byte[] s = ascii.GetBytes(inputString);
  580. for (int i = 0; i < s.Length; i++)
  581. {
  582. if ((int)s[i] == 63)
  583. {
  584. tempLen += 2;
  585. }
  586. else
  587. {
  588. tempLen += 1;
  589. }
  590. try
  591. {
  592. tempString += inputString.Substring(i, 1);
  593. }
  594. catch
  595. {
  596. break;
  597. }
  598. if (tempLen > len)
  599. break;
  600. }
  601. //如果截过则加上半个省略号
  602. byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
  603. if (mybyte.Length > len)
  604. tempString += "…";
  605. return tempString;
  606. }
  607. #endregion
  608. #region 清除HTML标记
  609. public static string DropHTML(string Htmlstring)
  610. {
  611. if (string.IsNullOrEmpty(Htmlstring)) return "";
  612. //删除脚本
  613. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  614. //删除HTML
  615. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  616. Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  617. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  618. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  619. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  620. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  621. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  622. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  623. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  624. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  625. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  626. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  627. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  628. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  629. Htmlstring.Replace("<", "");
  630. Htmlstring.Replace(">", "");
  631. Htmlstring.Replace("\r\n", "");
  632. Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  633. return Htmlstring;
  634. }
  635. #endregion
  636. #region 去除HTML标记
  637. ///<summary>
  638. ///去除HTML标记
  639. ///</summary>
  640. ///<param name="NoHTML">包括HTML的源码</param>
  641. ///<returns>已经去除后的文字</returns>
  642. public static string NoHTML(string Htmlstring)
  643. {
  644. //Regex myReg = new Regex(@"(\<.[^\<]*\>)", RegexOptions.IgnoreCase);
  645. //Htmlstring = myReg.Replace(Htmlstring, "");
  646. //myReg = new Regex(@"(\<\/[^\<]*\>)", RegexOptions.IgnoreCase);
  647. //Htmlstring = myReg.Replace(Htmlstring, "");
  648. //return Htmlstring;
  649. //删除脚本
  650. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  651. //删除HTML
  652. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  653. //Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  654. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  655. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  656. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  657. Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "“", RegexOptions.IgnoreCase);
  658. Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "”", RegexOptions.IgnoreCase);
  659. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  660. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  661. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  662. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  663. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  664. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  665. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  666. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  667. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  668. Htmlstring = Htmlstring.Replace("<", "&lt;");
  669. Htmlstring = Htmlstring.Replace(">", "&gt;");
  670. return Htmlstring;
  671. }
  672. #endregion
  673. /// <summary>
  674. /// 替换html中的特殊字符
  675. /// </summary>
  676. /// <param name="theString">需要进行替换的文本。</param>
  677. /// <returns>替换完的文本。</returns>
  678. public static string HtmlEncode(string theString)
  679. {
  680. theString = theString.Replace(">", "&gt;");
  681. theString = theString.Replace("<", "&lt;");
  682. theString = theString.Replace(" ", " &nbsp;");
  683. theString = theString.Replace("\"", "&quot;");
  684. theString = theString.Replace("'", "&#39;");
  685. theString = theString.Replace("\r\n", "<br/> ");
  686. return theString;
  687. }
  688. /// <summary>
  689. /// 恢复html中的特殊字符
  690. /// </summary>
  691. /// <param name="theString">需要恢复的文本。</param>
  692. /// <returns>恢复好的文本。</returns>
  693. public static string HtmlDecode(string theString)
  694. {
  695. theString = theString.Replace("&gt;", ">");
  696. theString = theString.Replace("&lt;", "<");
  697. theString = theString.Replace(" &nbsp;", " ");
  698. theString = theString.Replace("&quot;", "\"");
  699. theString = theString.Replace("&#39;", "'");
  700. theString = theString.Replace("<br/> ", "\r\n");
  701. theString = theString.Replace("&mdash;", "—");//2012-05-07新加的
  702. return theString;
  703. }
  704. #region 清除HTML标记且返回相应的长度
  705. public static string DropHTML(string Htmlstring, int strLen)
  706. {
  707. return CutString(DropHTML(Htmlstring), strLen);
  708. }
  709. #endregion
  710. #region TXT代码转换成HTML格式
  711. /// <summary>
  712. /// 字符串字符处理
  713. /// </summary>
  714. /// <param name="chr">等待处理的字符串</param>
  715. /// <returns>处理后的字符串</returns>
  716. /// //把TXT代码转换成HTML格式
  717. public static String ToHtml(string Input)
  718. {
  719. StringBuilder sb = new StringBuilder(Input);
  720. sb.Replace("&", "&amp;");
  721. sb.Replace("<", "&lt;");
  722. sb.Replace(">", "&gt;");
  723. sb.Replace("\r\n", "<br />");
  724. sb.Replace("\n", "<br />");
  725. sb.Replace("\t", " ");
  726. //sb.Replace(" ", "&nbsp;");
  727. return sb.ToString();
  728. }
  729. #endregion
  730. #region HTML代码转换成TXT格式
  731. /// <summary>
  732. /// 字符串字符处理
  733. /// </summary>
  734. /// <param name="chr">等待处理的字符串</param>
  735. /// <returns>处理后的字符串</returns>
  736. /// //把HTML代码转换成TXT格式
  737. public static String ToTxt(String Input)
  738. {
  739. StringBuilder sb = new StringBuilder(Input);
  740. sb.Replace("&nbsp;", " ");
  741. sb.Replace("<br>", "\r\n");
  742. sb.Replace("<br>", "\n");
  743. sb.Replace("<br />", "\n");
  744. sb.Replace("<br />", "\r\n");
  745. sb.Replace("&lt;", "<");
  746. sb.Replace("&gt;", ">");
  747. sb.Replace("&amp;", "&");
  748. return sb.ToString();
  749. }
  750. #endregion
  751. #region 检测是否有Sql危险字符
  752. /// <summary>
  753. /// 检测是否有Sql危险字符
  754. /// </summary>
  755. /// <param name="str">要判断字符串</param>
  756. /// <returns>判断结果,如果安全,则返回true,否则返回false</returns>
  757. public static bool IsSafeSqlString(string str)
  758. {
  759. return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
  760. }
  761. /// <summary>
  762. /// 检查危险字符
  763. /// </summary>
  764. /// <param name="Input"></param>
  765. /// <returns></returns>
  766. public static string Filter(string sInput)
  767. {
  768. if (sInput == null || sInput == "")
  769. return null;
  770. string sInput1 = sInput.ToLower();
  771. string output = sInput;
  772. string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
  773. if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
  774. {
  775. throw new Exception("字符串中含有非法字符!");
  776. }
  777. else
  778. {
  779. output = output.Replace("'", "''");
  780. }
  781. return output;
  782. }
  783. /// <summary>
  784. /// 检查过滤设定的危险字符
  785. /// </summary>
  786. /// <param name="InText">要过滤的字符串 </param>
  787. /// <returns>如果参数存在不安全字符,则返回true </returns>
  788. public static bool SqlFilter(string word, string InText)
  789. {
  790. if (InText == null)
  791. return false;
  792. foreach (string i in word.Split('|'))
  793. {
  794. if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
  795. {
  796. return true;
  797. }
  798. }
  799. return false;
  800. }
  801. #endregion
  802. #region 过滤特殊字符
  803. /// <summary>
  804. /// 过滤特殊字符
  805. /// </summary>
  806. /// <param name="Input"></param>
  807. /// <returns></returns>
  808. public static string Htmls(string Input)
  809. {
  810. if (Input != string.Empty && Input != null)
  811. {
  812. string ihtml = Input.ToLower();
  813. ihtml = ihtml.Replace("<script", "&lt;script");
  814. ihtml = ihtml.Replace("script>", "script&gt;");
  815. ihtml = ihtml.Replace("<%", "&lt;%");
  816. ihtml = ihtml.Replace("%>", "%&gt;");
  817. ihtml = ihtml.Replace("<$", "&lt;$");
  818. ihtml = ihtml.Replace("$>", "$&gt;");
  819. return ihtml;
  820. }
  821. else
  822. {
  823. return string.Empty;
  824. }
  825. }
  826. #endregion
  827. #region 检查是否为IP地址
  828. /// <summary>
  829. /// 是否为ip
  830. /// </summary>
  831. /// <param name="ip"></param>
  832. /// <returns></returns>
  833. public static bool IsIP(string ip)
  834. {
  835. 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?)$");
  836. }
  837. #endregion
  838. #region 获得配置文件节点XML文件的绝对路径
  839. public static string GetXmlMapPath(string xmlName)
  840. {
  841. return GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString());
  842. }
  843. /// <summary>
  844. /// datetime:2013-11-20
  845. /// author:lipu
  846. /// function:获得webconfig文件里,appSettings节点里的值
  847. /// </summary>
  848. /// <param name="keyStr"></param>
  849. /// <returns></returns>
  850. public static string GetAppSettingValue(string keyStr)
  851. {
  852. if (ConfigurationManager.AppSettings[keyStr] == null)
  853. {
  854. return "";
  855. }
  856. else
  857. {
  858. return ConfigurationManager.AppSettings[keyStr].ToString();
  859. }
  860. }
  861. #endregion
  862. #region 获得当前绝对路径
  863. /// <summary>
  864. /// 获得当前绝对路径
  865. /// </summary>
  866. /// <param name="strPath">指定的路径</param>
  867. /// <returns>绝对路径</returns>
  868. public static string GetMapPath(string strPath)
  869. {
  870. if (strPath.ToLower().StartsWith("http://"))
  871. {
  872. return strPath;
  873. }
  874. if (HttpContext.Current != null)
  875. {
  876. return HttpContext.Current.Server.MapPath(strPath);
  877. }
  878. else //非web程序引用
  879. {
  880. strPath = strPath.Replace("/", "\\");
  881. if (strPath.StartsWith("\\"))
  882. {
  883. strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
  884. }
  885. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
  886. }
  887. }
  888. #endregion
  889. #region 文件操作
  890. /// <summary>
  891. /// 删除单个文件
  892. /// </summary>
  893. /// <param name="_filepath">文件相对路径</param>
  894. public static bool DeleteFile(string _filepath)
  895. {
  896. if (string.IsNullOrEmpty(_filepath))
  897. {
  898. return false;
  899. }
  900. string fullpath = GetMapPath(_filepath);
  901. if (File.Exists(fullpath))
  902. {
  903. File.Delete(fullpath);
  904. return true;
  905. }
  906. return false;
  907. }
  908. /// <summary>
  909. /// 删除上传的文件(及缩略图)
  910. /// </summary>
  911. /// <param name="_filepath"></param>
  912. public static void DeleteUpFile(string _filepath)
  913. {
  914. if (string.IsNullOrEmpty(_filepath))
  915. {
  916. return;
  917. }
  918. string fullpath = GetMapPath(_filepath); //原图
  919. if (File.Exists(fullpath))
  920. {
  921. File.Delete(fullpath);
  922. }
  923. if (_filepath.LastIndexOf("/") >= 0)
  924. {
  925. string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);
  926. string fullTPATH = GetMapPath(thumbnailpath); //宿略图
  927. if (File.Exists(fullTPATH))
  928. {
  929. File.Delete(fullTPATH);
  930. }
  931. }
  932. }
  933. /// <summary>
  934. /// 删除指定文件夹
  935. /// </summary>
  936. /// <param name="_dirpath">文件相对路径</param>
  937. public static bool DeleteDirectory(string _dirpath)
  938. {
  939. if (string.IsNullOrEmpty(_dirpath))
  940. {
  941. return false;
  942. }
  943. string fullpath = GetMapPath(_dirpath);
  944. if (Directory.Exists(fullpath))
  945. {
  946. Directory.Delete(fullpath, true);
  947. return true;
  948. }
  949. return false;
  950. }
  951. /// <summary>
  952. /// 修改指定文件夹名称
  953. /// </summary>
  954. /// <param name="old_dirpath">旧相对路径</param>
  955. /// <param name="new_dirpath">新相对路径</param>
  956. /// <returns>bool</returns>
  957. public static bool MoveDirectory(string old_dirpath, string new_dirpath)
  958. {
  959. if (string.IsNullOrEmpty(old_dirpath))
  960. {
  961. return false;
  962. }
  963. string fulloldpath = GetMapPath(old_dirpath);
  964. string fullnewpath = GetMapPath(new_dirpath);
  965. if (Directory.Exists(fulloldpath))
  966. {
  967. Directory.Move(fulloldpath, fullnewpath);
  968. return true;
  969. }
  970. return false;
  971. }
  972. /// <summary>
  973. /// 返回文件大小KB
  974. /// </summary>
  975. /// <param name="_filepath">文件相对路径</param>
  976. /// <returns>int</returns>
  977. public static int GetFileSize(string _filepath)
  978. {
  979. if (string.IsNullOrEmpty(_filepath))
  980. {
  981. return 0;
  982. }
  983. string fullpath = GetMapPath(_filepath);
  984. if (File.Exists(fullpath))
  985. {
  986. FileInfo fileInfo = new FileInfo(fullpath);
  987. return ((int)fileInfo.Length) / 1024;
  988. }
  989. return 0;
  990. }
  991. /// <summary>
  992. /// 返回文件扩展名,不含“.”
  993. /// </summary>
  994. /// <param name="_filepath">文件全名称</param>
  995. /// <returns>string</returns>
  996. public static string GetFileExt(string _filepath)
  997. {
  998. if (string.IsNullOrEmpty(_filepath))
  999. {
  1000. return "";
  1001. }
  1002. if (_filepath.LastIndexOf(".") > 0)
  1003. {
  1004. return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
  1005. }
  1006. return "";
  1007. }
  1008. /// <summary>
  1009. /// 返回文件名,不含路径
  1010. /// </summary>
  1011. /// <param name="_filepath">文件相对路径</param>
  1012. /// <returns>string</returns>
  1013. public static string GetFileName(string _filepath)
  1014. {
  1015. return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);
  1016. }
  1017. /// <summary>
  1018. /// 文件是否存在
  1019. /// </summary>
  1020. /// <param name="_filepath">文件相对路径</param>
  1021. /// <returns>bool</returns>
  1022. public static bool FileExists(string _filepath)
  1023. {
  1024. string fullpath = GetMapPath(_filepath);
  1025. if (File.Exists(fullpath))
  1026. {
  1027. return true;
  1028. }
  1029. return false;
  1030. }
  1031. #endregion
  1032. #region 读取或写入cookie
  1033. /// <summary>
  1034. /// 写cookie值
  1035. /// </summary>
  1036. /// <param name="strName">名称</param>
  1037. /// <param name="strValue">值</param>
  1038. public static void WriteCookie(string strName, string strValue)
  1039. {
  1040. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1041. if (cookie == null)
  1042. {
  1043. cookie = new HttpCookie(strName);
  1044. }
  1045. cookie.Value = UrlEncode(strValue);
  1046. HttpContext.Current.Response.AppendCookie(cookie);
  1047. }
  1048. /// <summary>
  1049. /// 写cookie值
  1050. /// </summary>
  1051. /// <param name="strName">名称</param>
  1052. /// <param name="strValue">值</param>
  1053. public static void WriteCookie(string strName, string key, string strValue)
  1054. {
  1055. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1056. if (cookie == null)
  1057. {
  1058. cookie = new HttpCookie(strName);
  1059. }
  1060. cookie[key] = UrlEncode(strValue);
  1061. HttpContext.Current.Response.AppendCookie(cookie);
  1062. }
  1063. /// <summary>
  1064. /// 写cookie值
  1065. /// </summary>
  1066. /// <param name="strName">名称</param>
  1067. /// <param name="strValue">值</param>
  1068. public static void WriteCookie(string strName, string key, string strValue, int expires)
  1069. {
  1070. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1071. if (cookie == null)
  1072. {
  1073. cookie = new HttpCookie(strName);
  1074. }
  1075. cookie[key] = UrlEncode(strValue);
  1076. cookie.Expires = DateTime.Now.AddMinutes(expires);
  1077. HttpContext.Current.Response.AppendCookie(cookie);
  1078. }
  1079. /// <summary>
  1080. /// 写cookie值
  1081. /// </summary>
  1082. /// <param name="strName">名称</param>
  1083. /// <param name="strValue">值</param>
  1084. /// <param name="strValue">过期时间(分钟)</param>
  1085. public static void WriteCookie(string strName, string strValue, int expires)
  1086. {
  1087. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1088. if (cookie == null)
  1089. {
  1090. cookie = new HttpCookie(strName);
  1091. }
  1092. cookie.Value = UrlEncode(strValue);
  1093. cookie.Expires = DateTime.Now.AddMinutes(expires);
  1094. HttpContext.Current.Response.AppendCookie(cookie);
  1095. }
  1096. /// <summary>
  1097. /// 读cookie值
  1098. /// </summary>
  1099. /// <param name="strName">名称</param>
  1100. /// <returns>cookie值</returns>
  1101. public static string GetCookie(string strName)
  1102. {
  1103. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  1104. return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
  1105. return "";
  1106. }
  1107. /// <summary>
  1108. /// 读cookie值
  1109. /// </summary>
  1110. /// <param name="strName">名称</param>
  1111. /// <returns>cookie值</returns>
  1112. public static string GetCookie(string strName, string key)
  1113. {
  1114. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
  1115. return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
  1116. return "";
  1117. }
  1118. #endregion
  1119. #region 替换指定的字符串
  1120. /// <summary>
  1121. /// 替换指定的字符串
  1122. /// </summary>
  1123. /// <param name="originalStr">原字符串</param>
  1124. /// <param name="oldStr">旧字符串</param>
  1125. /// <param name="newStr">新字符串</param>
  1126. /// <returns></returns>
  1127. public static string ReplaceStr(string originalStr, string oldStr, string newStr)
  1128. {
  1129. if (string.IsNullOrEmpty(oldStr))
  1130. {
  1131. return "";
  1132. }
  1133. return originalStr.Replace(oldStr, newStr);
  1134. }
  1135. #endregion
  1136. #region 显示分页
  1137. /// <summary>
  1138. /// 返回分页页码
  1139. /// </summary>
  1140. /// <param name="pageSize">页面大小</param>
  1141. /// <param name="pageIndex">当前页</param>
  1142. /// <param name="totalCount">总记录数</param>
  1143. /// <param name="linkUrl">链接地址,__id__代表页码</param>
  1144. /// <param name="centSize">中间页码数量</param>
  1145. /// <returns></returns>
  1146. public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize)
  1147. {
  1148. //计算页数
  1149. if (totalCount < 1 || pageSize < 1)
  1150. {
  1151. return "";
  1152. }
  1153. int pageCount = totalCount / pageSize;
  1154. if (pageCount < 1)
  1155. {
  1156. return "";
  1157. }
  1158. if (totalCount % pageSize > 0)
  1159. {
  1160. pageCount += 1;
  1161. }
  1162. if (pageCount <= 1)
  1163. {
  1164. return "";
  1165. }
  1166. StringBuilder pageStr = new StringBuilder();
  1167. string pageId = "__id__";
  1168. string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">«上一页</a>";
  1169. string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页»</a>";
  1170. string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>";
  1171. string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>";
  1172. if (pageIndex <= 1)
  1173. {
  1174. firstBtn = "<span class=\"disabled\">«上一页</span>";
  1175. }
  1176. if (pageIndex >= pageCount)
  1177. {
  1178. lastBtn = "<span class=\"disabled\">下一页»</span>";
  1179. }
  1180. if (pageIndex == 1)
  1181. {
  1182. firstStr = "<span class=\"current\">1</span>";
  1183. }
  1184. if (pageIndex == pageCount)
  1185. {
  1186. lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";
  1187. }
  1188. int firstNum = pageIndex - (centSize / 2); //中间开始的页码
  1189. if (pageIndex < centSize)
  1190. firstNum = 2;
  1191. int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中间结束的页码
  1192. if (lastNum >= pageCount)
  1193. lastNum = pageCount - 1;
  1194. pageStr.Append("<span>共" + totalCount + "记录</span>");
  1195. pageStr.Append(firstBtn + firstStr);
  1196. if (pageIndex >= centSize)
  1197. {
  1198. pageStr.Append("<span>...</span>\n");
  1199. }
  1200. for (int i = firstNum; i <= lastNum; i++)
  1201. {
  1202. if (i == pageIndex)
  1203. {
  1204. pageStr.Append("<span class=\"current\">" + i + "</span>");
  1205. }
  1206. else
  1207. {
  1208. pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>");
  1209. }
  1210. }
  1211. if (pageCount - pageIndex > centSize - ((centSize / 2)))
  1212. {
  1213. pageStr.Append("<span>...</span>");
  1214. }
  1215. pageStr.Append(lastStr + lastBtn);
  1216. return pageStr.ToString();
  1217. }
  1218. #endregion
  1219. #region URL处理
  1220. /// <summary>
  1221. /// URL字符编码
  1222. /// </summary>
  1223. public static string UrlEncode(string str)
  1224. {
  1225. if (string.IsNullOrEmpty(str))
  1226. {
  1227. return "";
  1228. }
  1229. str = str.Replace("'", "");
  1230. return HttpContext.Current.Server.UrlEncode(str);
  1231. }
  1232. /// <summary>
  1233. /// URL字符解码
  1234. /// </summary>
  1235. public static string UrlDecode(string str)
  1236. {
  1237. if (string.IsNullOrEmpty(str))
  1238. {
  1239. return "";
  1240. }
  1241. return HttpContext.Current.Server.UrlDecode(str);
  1242. }
  1243. /// <summary>
  1244. /// 组合URL参数
  1245. /// </summary>
  1246. /// <param name="_url">页面地址</param>
  1247. /// <param name="_keys">参数名称</param>
  1248. /// <param name="_values">参数值</param>
  1249. /// <returns>String</returns>
  1250. public static string CombUrlTxt(string _url, string _keys, params string[] _values)
  1251. {
  1252. StringBuilder urlParams = new StringBuilder();
  1253. try
  1254. {
  1255. string[] keyArr = _keys.Split(new char[] { '&' });
  1256. for (int i = 0; i < keyArr.Length; i++)
  1257. {
  1258. if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
  1259. {
  1260. _values[i] = UrlEncode(_values[i]);
  1261. urlParams.Append(string.Format(keyArr[i], _values) + "&");
  1262. }
  1263. }
  1264. if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
  1265. urlParams.Insert(0, "?");
  1266. //李朴-----add 2014-3-30 begin ----
  1267. if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.Contains("&") && _url.LastIndexOf("&") < (_url.Length - 1))
  1268. {
  1269. _url += "&";
  1270. }
  1271. //李朴-----add 2014-3-30 end ----
  1272. }
  1273. catch
  1274. {
  1275. return _url;
  1276. }
  1277. return _url + DelLastChar(urlParams.ToString(), "&");
  1278. }
  1279. #endregion
  1280. #region URL请求数据
  1281. /// <summary>
  1282. /// HTTP POST方式请求数据
  1283. /// </summary>
  1284. /// <param name="url">URL.</param>
  1285. /// <param name="param">POST的数据</param>
  1286. /// <returns></returns>
  1287. public static string HttpPost(string url, string param)
  1288. {
  1289. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1290. request.Method = "POST";
  1291. request.ContentType = "application/x-www-form-urlencoded";
  1292. request.Accept = "*/*";
  1293. request.Timeout = 15000;
  1294. request.AllowAutoRedirect = false;
  1295. StreamWriter requestStream = null;
  1296. WebResponse response = null;
  1297. string responseStr = null;
  1298. try
  1299. {
  1300. requestStream = new StreamWriter(request.GetRequestStream());
  1301. requestStream.Write(param);
  1302. requestStream.Close();
  1303. response = request.GetResponse();
  1304. if (response != null)
  1305. {
  1306. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  1307. responseStr = reader.ReadToEnd();
  1308. reader.Close();
  1309. }
  1310. }
  1311. catch (Exception)
  1312. {
  1313. throw;
  1314. }
  1315. finally
  1316. {
  1317. request = null;
  1318. requestStream = null;
  1319. response = null;
  1320. }
  1321. return responseStr;
  1322. }
  1323. /// <summary>
  1324. /// HTTP GET方式请求数据.
  1325. /// </summary>
  1326. /// <param name="url">URL.</param>
  1327. /// <returns></returns>
  1328. public static string HttpGet(string url)
  1329. {
  1330. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1331. request.Method = "GET";
  1332. //request.ContentType = "application/x-www-form-urlencoded";
  1333. request.Accept = "*/*";
  1334. request.Timeout = 15000;
  1335. request.AllowAutoRedirect = false;
  1336. WebResponse response = null;
  1337. string responseStr = null;
  1338. try
  1339. {
  1340. response = request.GetResponse();
  1341. if (response != null)
  1342. {
  1343. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  1344. responseStr = reader.ReadToEnd();
  1345. reader.Close();
  1346. }
  1347. }
  1348. catch (Exception)
  1349. {
  1350. throw;
  1351. }
  1352. finally
  1353. {
  1354. request = null;
  1355. response = null;
  1356. }
  1357. return responseStr;
  1358. }
  1359. /// <summary>
  1360. /// 执行URL获取页面内容
  1361. /// </summary>
  1362. public static string UrlExecute(string urlPath)
  1363. {
  1364. if (string.IsNullOrEmpty(urlPath))
  1365. {
  1366. return "error";
  1367. }
  1368. StringWriter sw = new StringWriter();
  1369. try
  1370. {
  1371. HttpContext.Current.Server.Execute(urlPath, sw);
  1372. return sw.ToString();
  1373. }
  1374. catch (Exception)
  1375. {
  1376. return "error";
  1377. }
  1378. finally
  1379. {
  1380. sw.Close();
  1381. sw.Dispose();
  1382. }
  1383. }
  1384. #endregion
  1385. #region 操作权限菜单
  1386. /// <summary>
  1387. /// 获取操作权限
  1388. /// </summary>
  1389. /// <returns>Dictionary</returns>
  1390. public static Dictionary<string, string> ActionType()
  1391. {
  1392. Dictionary<string, string> dic = new Dictionary<string, string>();
  1393. dic.Add("Show", "显示");
  1394. dic.Add("View", "查看");
  1395. dic.Add("Add", "添加");
  1396. dic.Add("Edit", "修改");
  1397. dic.Add("Delete", "删除");
  1398. dic.Add("Audit", "审核");
  1399. dic.Add("Reply", "回复");
  1400. dic.Add("Confirm", "确认");
  1401. dic.Add("Cancel", "取消");
  1402. dic.Add("Invalid", "作废");
  1403. dic.Add("Build", "生成");
  1404. dic.Add("Instal", "安装");
  1405. dic.Add("Unload", "卸载");
  1406. dic.Add("Back", "备份");
  1407. dic.Add("Restore", "还原");
  1408. dic.Add("Replace", "替换");
  1409. return dic;
  1410. }
  1411. #endregion
  1412. #region 替换URL
  1413. /// <summary>
  1414. /// 替换扩展名
  1415. /// </summary>
  1416. public static string GetUrlExtension(string urlPage, string staticExtension)
  1417. {
  1418. int indexNum = urlPage.LastIndexOf('.');
  1419. if (indexNum > 0)
  1420. {
  1421. return urlPage.Replace(urlPage.Substring(indexNum), "." + staticExtension);
  1422. }
  1423. return urlPage;
  1424. }
  1425. /// <summary>
  1426. /// 替换扩展名,如没有扩展名替换默认首页
  1427. /// </summary>
  1428. public static string GetUrlExtension(string urlPage, string staticExtension, bool defaultVal)
  1429. {
  1430. int indexNum = urlPage.LastIndexOf('.');
  1431. if (indexNum > 0)
  1432. {
  1433. return urlPage.Replace(urlPage.Substring(indexNum), "." + staticExtension);
  1434. }
  1435. if (defaultVal)
  1436. {
  1437. if (urlPage.EndsWith("/"))
  1438. {
  1439. return urlPage + "index." + staticExtension;
  1440. }
  1441. else
  1442. {
  1443. return urlPage + "/index." + staticExtension;
  1444. }
  1445. }
  1446. return urlPage;
  1447. }
  1448. #endregion
  1449. /// <summary>
  1450. /// 字符串数组转字符串List
  1451. /// </summary>
  1452. /// <param name="strArray"></param>
  1453. /// <returns></returns>
  1454. public static List<string> StrArrayToList(string[] strArray)
  1455. {
  1456. List<string> list = new List<string>();
  1457. foreach (string s in strArray)
  1458. {
  1459. list.Add(s);
  1460. }
  1461. return list;
  1462. }
  1463. }
  1464. }