Utils.cs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  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.Web.Script.Serialization;
  11. using System.Data;
  12. using System.Collections;
  13. using System.Runtime.Serialization.Json;
  14. using System.Configuration;
  15. using System.Reflection;
  16. namespace Ant.Service.Common
  17. {
  18. /// <summary>
  19. /// 系统帮助类
  20. /// </summary>
  21. public class Utils
  22. {
  23. #region 对象转换处理
  24. /// <summary>
  25. /// 判断对象是否为Int32类型的数字
  26. /// </summary>
  27. /// <param name="Expression"></param>
  28. /// <returns></returns>
  29. public static bool IsNumeric(object expression)
  30. {
  31. if (expression != null)
  32. return IsNumeric(expression.ToString());
  33. return false;
  34. }
  35. /// <summary>
  36. /// 判断对象是否为Int32类型的数字
  37. /// </summary>
  38. /// <param name="Expression"></param>
  39. /// <returns></returns>
  40. public static bool IsNumeric(string expression)
  41. {
  42. if (expression != null)
  43. {
  44. string str = expression;
  45. if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))
  46. {
  47. if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. /// <summary>
  54. /// 是否为Double类型
  55. /// </summary>
  56. /// <param name="expression"></param>
  57. /// <returns></returns>
  58. public static bool IsDouble(object expression)
  59. {
  60. if (expression != null)
  61. return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
  62. return false;
  63. }
  64. /// <summary>
  65. /// 将字符串转换为数组
  66. /// </summary>
  67. /// <param name="str">字符串</param>
  68. /// <returns>字符串数组</returns>
  69. public static string[] GetStrArray(string str)
  70. {
  71. return str.Split(new char[',']);
  72. }
  73. /// <summary>
  74. /// 将数组转换为字符串
  75. /// </summary>
  76. /// <param name="list">List</param>
  77. /// <param name="speater">分隔符</param>
  78. /// <returns>String</returns>
  79. public static string GetArrayStr(List<string> list, string speater)
  80. {
  81. StringBuilder sb = new StringBuilder();
  82. for (int i = 0; i < list.Count; i++)
  83. {
  84. if (i == list.Count - 1)
  85. {
  86. sb.Append(list[i]);
  87. }
  88. else
  89. {
  90. sb.Append(list[i]);
  91. sb.Append(speater);
  92. }
  93. }
  94. return sb.ToString();
  95. }
  96. /// <summary>
  97. /// object型转换为bool型
  98. /// </summary>
  99. /// <param name="strValue">要转换的字符串</param>
  100. /// <param name="defValue">缺省值</param>
  101. /// <returns>转换后的bool类型结果</returns>
  102. public static bool StrToBool(object expression, bool defValue)
  103. {
  104. if (expression != null)
  105. return StrToBool(expression, defValue);
  106. return defValue;
  107. }
  108. /// <summary>
  109. /// string型转换为bool型
  110. /// </summary>
  111. /// <param name="strValue">要转换的字符串</param>
  112. /// <param name="defValue">缺省值</param>
  113. /// <returns>转换后的bool类型结果</returns>
  114. public static bool StrToBool(string expression, bool defValue)
  115. {
  116. if (expression != null)
  117. {
  118. if (string.Compare(expression, "true", true) == 0)
  119. return true;
  120. else if (string.Compare(expression, "false", true) == 0)
  121. return false;
  122. }
  123. return defValue;
  124. }
  125. /// <summary>
  126. /// 将对象转换为Int32类型
  127. /// </summary>
  128. /// <param name="expression">要转换的字符串</param>
  129. /// <param name="defValue">缺省值</param>
  130. /// <returns>转换后的int类型结果</returns>
  131. public static int ObjToInt(object expression, int defValue)
  132. {
  133. if (expression != null)
  134. return StrToInt(expression.ToString(), defValue);
  135. return defValue;
  136. }
  137. /// <summary>
  138. /// 将字符串转换为Int32类型
  139. /// </summary>
  140. /// <param name="expression">要转换的字符串</param>
  141. /// <param name="defValue">缺省值</param>
  142. /// <returns>转换后的int类型结果</returns>
  143. public static int StrToInt(string expression, int defValue)
  144. {
  145. if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
  146. return defValue;
  147. int rv;
  148. if (Int32.TryParse(expression, out rv))
  149. return rv;
  150. return Convert.ToInt32(StrToFloat(expression, defValue));
  151. }
  152. /// <summary>
  153. /// Object型转换为decimal型
  154. /// </summary>
  155. /// <param name="strValue">要转换的字符串</param>
  156. /// <param name="defValue">缺省值</param>
  157. /// <returns>转换后的decimal类型结果</returns>
  158. public static decimal ObjToDecimal(object expression, decimal defValue)
  159. {
  160. if (expression != null)
  161. return StrToDecimal(expression.ToString(), defValue);
  162. return defValue;
  163. }
  164. /// <summary>
  165. /// string型转换为decimal型
  166. /// </summary>
  167. /// <param name="strValue">要转换的字符串</param>
  168. /// <param name="defValue">缺省值</param>
  169. /// <returns>转换后的decimal类型结果</returns>
  170. public static decimal StrToDecimal(string expression, decimal defValue)
  171. {
  172. if ((expression == null) || (expression.Length > 10))
  173. return defValue;
  174. decimal intValue = defValue;
  175. if (expression != null)
  176. {
  177. bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
  178. if (IsDecimal)
  179. decimal.TryParse(expression, out intValue);
  180. }
  181. return intValue;
  182. }
  183. /// <summary>
  184. /// Object型转换为float型
  185. /// </summary>
  186. /// <param name="strValue">要转换的字符串</param>
  187. /// <param name="defValue">缺省值</param>
  188. /// <returns>转换后的int类型结果</returns>
  189. public static float ObjToFloat(object expression, float defValue)
  190. {
  191. if (expression != null)
  192. return StrToFloat(expression.ToString(), defValue);
  193. return defValue;
  194. }
  195. /// <summary>
  196. /// string型转换为float型
  197. /// </summary>
  198. /// <param name="strValue">要转换的字符串</param>
  199. /// <param name="defValue">缺省值</param>
  200. /// <returns>转换后的int类型结果</returns>
  201. public static float StrToFloat(string expression, float defValue)
  202. {
  203. if ((expression == null) || (expression.Length > 10))
  204. return defValue;
  205. float intValue = defValue;
  206. if (expression != null)
  207. {
  208. bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
  209. if (IsFloat)
  210. float.TryParse(expression, out intValue);
  211. }
  212. return intValue;
  213. }
  214. /// <summary>
  215. /// 将对象转换为日期时间类型
  216. /// </summary>
  217. /// <param name="str">要转换的字符串</param>
  218. /// <param name="defValue">缺省值</param>
  219. /// <returns>转换后的int类型结果</returns>
  220. public static DateTime StrToDateTime(string str, DateTime defValue)
  221. {
  222. if (!string.IsNullOrEmpty(str))
  223. {
  224. DateTime dateTime;
  225. if (DateTime.TryParse(str, out dateTime))
  226. return dateTime;
  227. }
  228. return defValue;
  229. }
  230. /// <summary>
  231. /// 将对象转换为日期时间类型
  232. /// </summary>
  233. /// <param name="str">要转换的字符串</param>
  234. /// <returns>转换后的int类型结果</returns>
  235. public static DateTime StrToDateTime(string str)
  236. {
  237. return StrToDateTime(str, DateTime.Now);
  238. }
  239. /// <summary>
  240. /// 将对象转换为日期时间类型
  241. /// </summary>
  242. /// <param name="obj">要转换的对象</param>
  243. /// <returns>转换后的int类型结果</returns>
  244. public static DateTime ObjectToDateTime(object obj)
  245. {
  246. return StrToDateTime(obj.ToString());
  247. }
  248. /// <summary>
  249. /// 将对象转换为日期时间类型
  250. /// </summary>
  251. /// <param name="obj">要转换的对象</param>
  252. /// <param name="defValue">缺省值</param>
  253. /// <returns>转换后的int类型结果</returns>
  254. public static DateTime ObjectToDateTime(object obj, DateTime defValue)
  255. {
  256. return StrToDateTime(obj.ToString(), defValue);
  257. }
  258. /// <summary>
  259. /// 将对象转换为字符串
  260. /// </summary>
  261. /// <param name="obj">要转换的对象</param>
  262. /// <returns>转换后的string类型结果</returns>
  263. public static string ObjectToStr(object obj)
  264. {
  265. if (obj == null)
  266. return "";
  267. return obj.ToString().Trim();
  268. }
  269. #endregion
  270. #region 分割字符串
  271. /// <summary>
  272. /// 分割字符串
  273. /// </summary>
  274. public static string[] SplitString(string strContent, string strSplit)
  275. {
  276. if (!string.IsNullOrEmpty(strContent))
  277. {
  278. if (strContent.IndexOf(strSplit) < 0)
  279. return new string[] { strContent };
  280. return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
  281. }
  282. else
  283. return new string[0] { };
  284. }
  285. /// <summary>
  286. /// 分割字符串
  287. /// </summary>
  288. /// <returns></returns>
  289. public static string[] SplitString(string strContent, string strSplit, int count)
  290. {
  291. string[] result = new string[count];
  292. string[] splited = SplitString(strContent, strSplit);
  293. for (int i = 0; i < count; i++)
  294. {
  295. if (i < splited.Length)
  296. result[i] = splited[i];
  297. else
  298. result[i] = string.Empty;
  299. }
  300. return result;
  301. }
  302. #endregion
  303. #region 截取字符串
  304. public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
  305. {
  306. return GetSubString(p_SrcString, 0, p_Length, p_TailString);
  307. }
  308. public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
  309. {
  310. string str = p_SrcString;
  311. byte[] bytes = Encoding.UTF8.GetBytes(p_SrcString);
  312. foreach (char ch in Encoding.UTF8.GetChars(bytes))
  313. {
  314. if (((ch > 'ࠀ') && (ch < '一')) || ((ch > 0xac00) && (ch < 0xd7a3)))
  315. {
  316. if (p_StartIndex >= p_SrcString.Length)
  317. {
  318. return "";
  319. }
  320. return p_SrcString.Substring(p_StartIndex, ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
  321. }
  322. }
  323. if (p_Length < 0)
  324. {
  325. return str;
  326. }
  327. byte[] sourceArray = Encoding.Default.GetBytes(p_SrcString);
  328. if (sourceArray.Length <= p_StartIndex)
  329. {
  330. return str;
  331. }
  332. int length = sourceArray.Length;
  333. if (sourceArray.Length > (p_StartIndex + p_Length))
  334. {
  335. length = p_Length + p_StartIndex;
  336. }
  337. else
  338. {
  339. p_Length = sourceArray.Length - p_StartIndex;
  340. p_TailString = "";
  341. }
  342. int num2 = p_Length;
  343. int[] numArray = new int[p_Length];
  344. byte[] destinationArray = null;
  345. int num3 = 0;
  346. for (int i = p_StartIndex; i < length; i++)
  347. {
  348. if (sourceArray[i] > 0x7f)
  349. {
  350. num3++;
  351. if (num3 == 3)
  352. {
  353. num3 = 1;
  354. }
  355. }
  356. else
  357. {
  358. num3 = 0;
  359. }
  360. numArray[i] = num3;
  361. }
  362. if ((sourceArray[length - 1] > 0x7f) && (numArray[p_Length - 1] == 1))
  363. {
  364. num2 = p_Length + 1;
  365. }
  366. destinationArray = new byte[num2];
  367. Array.Copy(sourceArray, p_StartIndex, destinationArray, 0, num2);
  368. return (Encoding.Default.GetString(destinationArray) + p_TailString);
  369. }
  370. #endregion
  371. #region 删除最后结尾的一个逗号
  372. /// <summary>
  373. /// 删除最后结尾的一个逗号
  374. /// </summary>
  375. public static string DelLastComma(string str)
  376. {
  377. return str.Substring(0, str.LastIndexOf(","));
  378. }
  379. #endregion
  380. #region 删除最后结尾的指定字符后的字符
  381. /// <summary>
  382. /// 删除最后结尾的指定字符后的字符
  383. /// </summary>
  384. public static string DelLastChar(string str, string strchar)
  385. {
  386. if (string.IsNullOrEmpty(str))
  387. return "";
  388. if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)
  389. {
  390. return str.Substring(0, str.LastIndexOf(strchar));
  391. }
  392. return str;
  393. }
  394. #endregion
  395. #region 生成指定长度的字符串
  396. /// <summary>
  397. /// 生成指定长度的字符串,即生成strLong个str字符串
  398. /// </summary>
  399. /// <param name="strLong">生成的长度</param>
  400. /// <param name="str">以str生成字符串</param>
  401. /// <returns></returns>
  402. public static string StringOfChar(int strLong, string str)
  403. {
  404. string ReturnStr = "";
  405. for (int i = 0; i < strLong; i++)
  406. {
  407. ReturnStr += str;
  408. }
  409. return ReturnStr;
  410. }
  411. #endregion
  412. #region 生成日期随机码
  413. /// <summary>
  414. /// 生成日期随机码
  415. /// </summary>
  416. /// <returns></returns>
  417. public static string GetRamCode()
  418. {
  419. #region
  420. return DateTime.Now.ToString("yyyyMMddHHmmssffff");
  421. #endregion
  422. }
  423. #endregion
  424. #region 生成随机字母或数字
  425. /// <summary>
  426. /// 生成随机数字
  427. /// </summary>
  428. /// <param name="length">生成长度</param>
  429. /// <returns></returns>
  430. public static string Number(int Length)
  431. {
  432. return Number(Length, false);
  433. }
  434. /// <summary>
  435. /// 生成随机数字
  436. /// </summary>
  437. /// <param name="Length">生成长度</param>
  438. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  439. /// <returns></returns>
  440. public static string Number(int Length, bool Sleep)
  441. {
  442. if (Sleep)
  443. System.Threading.Thread.Sleep(3);
  444. string result = "";
  445. System.Random random = new Random();
  446. for (int i = 0; i < Length; i++)
  447. {
  448. result += random.Next(10).ToString();
  449. }
  450. return result;
  451. }
  452. /// <summary>
  453. /// 生成随机字母字符串(数字字母混和)
  454. /// </summary>
  455. /// <param name="codeCount">待生成的位数</param>
  456. public static string GetCheckCode(int codeCount)
  457. {
  458. string str = string.Empty;
  459. int rep = 0;
  460. long num2 = DateTime.Now.Ticks + rep;
  461. rep++;
  462. Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
  463. for (int i = 0; i < codeCount; i++)
  464. {
  465. char ch;
  466. int num = random.Next();
  467. if ((num % 2) == 0)
  468. {
  469. ch = (char)(0x30 + ((ushort)(num % 10)));
  470. }
  471. else
  472. {
  473. ch = (char)(0x41 + ((ushort)(num % 0x1a)));
  474. }
  475. str = str + ch.ToString();
  476. }
  477. return str;
  478. }
  479. /// <summary>
  480. /// 根据日期和随机码生成订单号
  481. /// </summary>
  482. /// <returns></returns>
  483. public static string GetOrderNumber()
  484. {
  485. string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
  486. return num + Number(2).ToString();
  487. }
  488. private static int Next(int numSeeds, int length)
  489. {
  490. byte[] buffer = new byte[length];
  491. System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
  492. Gen.GetBytes(buffer);
  493. uint randomResult = 0x0;//这里用uint作为生成的随机数
  494. for (int i = 0; i < length; i++)
  495. {
  496. randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
  497. }
  498. return (int)(randomResult % numSeeds);
  499. }
  500. #endregion
  501. #region 截取字符长度
  502. /// <summary>
  503. /// 截取字符长度
  504. /// </summary>
  505. /// <param name="inputString">字符</param>
  506. /// <param name="len">长度</param>
  507. /// <returns></returns>
  508. public static string CutString(string inputString, int len)
  509. {
  510. if (string.IsNullOrEmpty(inputString))
  511. return "";
  512. inputString = DropHTML(inputString);
  513. ASCIIEncoding ascii = new ASCIIEncoding();
  514. int tempLen = 0;
  515. string tempString = "";
  516. byte[] s = ascii.GetBytes(inputString);
  517. for (int i = 0; i < s.Length; i++)
  518. {
  519. if ((int)s[i] == 63)
  520. {
  521. tempLen += 2;
  522. }
  523. else
  524. {
  525. tempLen += 1;
  526. }
  527. try
  528. {
  529. tempString += inputString.Substring(i, 1);
  530. }
  531. catch
  532. {
  533. break;
  534. }
  535. if (tempLen > len)
  536. break;
  537. }
  538. //如果截过则加上半个省略号
  539. byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
  540. if (mybyte.Length > len)
  541. tempString += "…";
  542. return tempString;
  543. }
  544. #endregion
  545. #region 对象<-->JSON 4.0使用
  546. /// <summary>
  547. /// 对象转JSON
  548. /// </summary>
  549. /// <typeparam name="T">对象实体</typeparam>
  550. /// <param name="t">内容</param>
  551. /// <returns>json包</returns>
  552. public static string ObjetcToJson<T>(T t)
  553. {
  554. try
  555. {
  556. DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
  557. string szJson = "";
  558. using (MemoryStream stream = new MemoryStream())
  559. {
  560. json.WriteObject(stream, t);
  561. szJson = Encoding.UTF8.GetString(stream.ToArray());
  562. }
  563. return szJson;
  564. }
  565. catch { return ""; }
  566. }
  567. /// <summary>
  568. /// Json包转对象
  569. /// </summary>
  570. /// <typeparam name="T">对象</typeparam>
  571. /// <param name="jsonstring">json包</param>
  572. /// <returns>异常抛null</returns>
  573. public static object JsonToObject<T>(string jsonstring)
  574. {
  575. object result = null;
  576. try
  577. {
  578. DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
  579. using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)))
  580. {
  581. result = json.ReadObject(stream);
  582. }
  583. return result;
  584. }
  585. catch { return result; }
  586. }
  587. #endregion
  588. #region 对象<-->JSON 2.0 使用litjson插件
  589. /// <summary>
  590. /// 对象转JSON jsonData
  591. /// </summary>
  592. /// <typeparam name="T"></typeparam>
  593. /// <param name="t"></param>
  594. /// <returns></returns>
  595. //public static string ObjetcToJsonData<T>(T t)
  596. //{
  597. // try
  598. // {
  599. // JsonData json = new JsonData(t);
  600. // return json.ToJson();
  601. // }
  602. // catch
  603. // {
  604. // return "";
  605. // }
  606. //}
  607. ///// <summary>
  608. ///// 对象转JSON jsonMapper
  609. ///// </summary>
  610. ///// <typeparam name="T"></typeparam>
  611. ///// <param name="t"></param>
  612. ///// <returns></returns>
  613. //public static string ObjetcToJsonMapper<T>(T t)
  614. //{
  615. // try
  616. // {
  617. // JsonData json = JsonMapper.ToJson(t);
  618. // return json.ToJson();
  619. // }
  620. // catch
  621. // {
  622. // return "";
  623. // }
  624. //}
  625. ///// <summary>
  626. ///// json转对象 jsonMapper
  627. ///// </summary>
  628. ///// <param name="jsons"></param>
  629. ///// <returns></returns>
  630. //public static object JsonToObject(string jsons)
  631. //{
  632. // try
  633. // {
  634. // JsonData jsonObject = JsonMapper.ToObject(jsons);
  635. // return jsonObject;
  636. // }
  637. // catch { return null; }
  638. //}
  639. #endregion
  640. #region DataTable<-->JSON
  641. /// <summary>
  642. /// DataTable转为json
  643. /// </summary>
  644. /// <param name="dt">DataTable</param>
  645. /// <returns>json数据</returns>
  646. public static string DataTableToJson(DataTable dt)
  647. {
  648. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  649. foreach (DataRow dr in dt.Rows)
  650. {
  651. Dictionary<string, object> result = new Dictionary<string, object>();
  652. foreach (DataColumn dc in dt.Columns)
  653. {
  654. result.Add(dc.ColumnName, dr[dc]);
  655. }
  656. list.Add(result);
  657. }
  658. return SerializeToJson(list);
  659. }
  660. /// <summary>
  661. /// 序列化对象为Json字符串
  662. /// </summary>
  663. /// <param name="obj">要序列化的对象</param>
  664. /// <param name="recursionLimit">序列化对象的深度,默认为100</param>
  665. /// <returns>Json字符串</returns>
  666. public static string SerializeToJson(object obj, int recursionLimit = 100)
  667. {
  668. try
  669. {
  670. JavaScriptSerializer serialize = new JavaScriptSerializer();
  671. serialize.RecursionLimit = recursionLimit;
  672. return serialize.Serialize(obj);
  673. }
  674. catch { return ""; }
  675. }
  676. /// <summary>
  677. /// json包转DataTable
  678. /// </summary>
  679. /// <param name="jsons"></param>
  680. /// <returns></returns>
  681. public static DataTable JsonToDataTable(string jsons)
  682. {
  683. DataTable dt = new DataTable();
  684. try
  685. {
  686. JavaScriptSerializer serialize = new JavaScriptSerializer();
  687. serialize.MaxJsonLength = Int32.MaxValue;
  688. ArrayList list = serialize.Deserialize<ArrayList>(jsons);
  689. if (list.Count > 0)
  690. {
  691. foreach (Dictionary<string, object> item in list)
  692. {
  693. if (item.Keys.Count == 0)//无值返回空
  694. {
  695. return dt;
  696. }
  697. if (dt.Columns.Count == 0)//初始Columns
  698. {
  699. foreach (string current in item.Keys)
  700. {
  701. dt.Columns.Add(current, item[current].GetType());
  702. }
  703. }
  704. DataRow dr = dt.NewRow();
  705. foreach (string current in item.Keys)
  706. {
  707. dr[current] = item[current];
  708. }
  709. dt.Rows.Add(dr);
  710. }
  711. }
  712. }
  713. catch
  714. {
  715. return dt;
  716. }
  717. return dt;
  718. }
  719. #endregion
  720. #region List<--->DataTable
  721. /// <summary>
  722. /// DataTable转换泛型集合
  723. /// </summary>
  724. /// <typeparam name="T"></typeparam>
  725. /// <param name="table"></param>
  726. /// <returns></returns>
  727. public static List<T> DataTableToList<T>(DataTable table)
  728. {
  729. List<T> list = new List<T>();
  730. T t = default(T);
  731. PropertyInfo[] propertypes = null;
  732. string tempName = string.Empty;
  733. foreach (DataRow row in table.Rows)
  734. {
  735. t = Activator.CreateInstance<T>();
  736. propertypes = t.GetType().GetProperties();
  737. foreach (PropertyInfo pro in propertypes)
  738. {
  739. tempName = pro.Name;
  740. if (table.Columns.Contains(tempName))
  741. {
  742. object value = row[tempName];
  743. if (!value.ToString().Equals(""))
  744. {
  745. pro.SetValue(t, value, null);
  746. }
  747. }
  748. }
  749. list.Add(t);
  750. }
  751. return list.Count == 0 ? null : list;
  752. }
  753. /// <summary>
  754. /// 将集合类转换成DataTable
  755. /// </summary>
  756. /// <param name="list">集合</param>
  757. /// <returns>DataTable</returns>
  758. public static DataTable ListToDataTable(IList list)
  759. {
  760. DataTable result = new DataTable();
  761. if (list != null && list.Count > 0)
  762. {
  763. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  764. foreach (PropertyInfo pi in propertys)
  765. {
  766. result.Columns.Add(pi.Name, pi.PropertyType);
  767. }
  768. for (int i = 0; i < list.Count; i++)
  769. {
  770. ArrayList tempList = new ArrayList();
  771. foreach (PropertyInfo pi in propertys)
  772. {
  773. object obj = pi.GetValue(list[i], null);
  774. tempList.Add(obj);
  775. }
  776. object[] array = tempList.ToArray();
  777. result.LoadDataRow(array, true);
  778. }
  779. }
  780. return result;
  781. }
  782. public static List<T> ConvertTo<T>(DataTable dt) where T : new()
  783. {
  784. if (dt == null) return null;
  785. if (dt.Rows.Count <= 0) return null;
  786. List<T> list = new List<T>();
  787. try
  788. {
  789. List<string> columnsName = new List<string>();
  790. foreach (DataColumn dataColumn in dt.Columns)
  791. {
  792. columnsName.Add(dataColumn.ColumnName);//得到所有的表头
  793. }
  794. list = dt.AsEnumerable().ToList().ConvertAll<T>(row => GetObject<T>(row, columnsName)); //转换
  795. return list;
  796. }
  797. catch
  798. {
  799. return null;
  800. }
  801. }
  802. public static T GetObject<T>(DataRow row, List<string> columnsName) where T : new()
  803. {
  804. T obj = new T();
  805. try
  806. {
  807. string columnname = "";
  808. string value = "";
  809. PropertyInfo[] Properties = typeof(T).GetProperties();
  810. foreach (PropertyInfo objProperty in Properties) //遍历T的属性
  811. {
  812. columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower()); //寻找可以匹配的表头名称
  813. if (!string.IsNullOrEmpty(columnname))
  814. {
  815. value = row[columnname].ToString();
  816. if (!string.IsNullOrEmpty(value))
  817. {
  818. if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) //存在匹配的表头
  819. {
  820. value = row[columnname].ToString().Replace("$", "").Replace(",", ""); //从dataRow中提取数据
  821. objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null); //赋值操作
  822. }
  823. else
  824. {
  825. value = row[columnname].ToString().Replace("%", ""); //存在匹配的表头
  826. objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);//赋值操作
  827. }
  828. }
  829. }
  830. }
  831. return obj;
  832. }
  833. catch
  834. {
  835. return obj;
  836. }
  837. }
  838. /// <summary>
  839. /// 将泛型集合类转换成DataTable
  840. /// </summary>
  841. /// <typeparam name="T">集合项类型</typeparam>
  842. /// <param name="list">集合</param>
  843. /// <param name="propertyName">需要返回的列的列名</param>
  844. /// <returns>数据集(表)</returns>
  845. public static DataTable ListToDataTable<T>(IList<T> list, params string[] propertyName)
  846. {
  847. List<string> propertyNameList = new List<string>();
  848. if (propertyName != null)
  849. propertyNameList.AddRange(propertyName);
  850. DataTable result = new DataTable();
  851. if (list != null && list.Count > 0)
  852. {
  853. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  854. foreach (PropertyInfo pi in propertys)
  855. {
  856. if (propertyNameList.Count == 0)
  857. {
  858. result.Columns.Add(pi.Name, pi.PropertyType);
  859. }
  860. else
  861. {
  862. if (propertyNameList.Contains(pi.Name))
  863. result.Columns.Add(pi.Name, pi.PropertyType);
  864. }
  865. }
  866. for (int i = 0; i < list.Count; i++)
  867. {
  868. ArrayList tempList = new ArrayList();
  869. foreach (PropertyInfo pi in propertys)
  870. {
  871. if (propertyNameList.Count == 0)
  872. {
  873. object obj = pi.GetValue(list[i], null);
  874. tempList.Add(obj);
  875. }
  876. else
  877. {
  878. if (propertyNameList.Contains(pi.Name))
  879. {
  880. object obj = pi.GetValue(list[i], null);
  881. tempList.Add(obj);
  882. }
  883. }
  884. }
  885. object[] array = tempList.ToArray();
  886. result.LoadDataRow(array, true);
  887. }
  888. }
  889. return result;
  890. }
  891. #endregion
  892. #region 清除HTML标记
  893. public static string DropHTML(string Htmlstring)
  894. {
  895. if (string.IsNullOrEmpty(Htmlstring)) return "";
  896. //删除脚本
  897. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  898. //删除HTML
  899. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  900. Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  901. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  902. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  903. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  904. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  905. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  906. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  907. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  908. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  909. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  910. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  911. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  912. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  913. Htmlstring.Replace("<", "");
  914. Htmlstring.Replace(">", "");
  915. Htmlstring.Replace("\r\n", "");
  916. Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  917. return Htmlstring;
  918. }
  919. #endregion
  920. #region 清除HTML标记且返回相应的长度
  921. public static string DropHTML(string Htmlstring, int strLen)
  922. {
  923. return CutString(DropHTML(Htmlstring), strLen);
  924. }
  925. #endregion
  926. #region TXT代码转换成HTML格式
  927. /// <summary>
  928. /// 字符串字符处理
  929. /// </summary>
  930. /// <param name="chr">等待处理的字符串</param>
  931. /// <returns>处理后的字符串</returns>
  932. /// //把TXT代码转换成HTML格式
  933. public static String ToHtml(string Input)
  934. {
  935. StringBuilder sb = new StringBuilder(Input);
  936. sb.Replace("&", "&amp;");
  937. sb.Replace("<", "&lt;");
  938. sb.Replace(">", "&gt;");
  939. sb.Replace("\r\n", "<br />");
  940. sb.Replace("\n", "<br />");
  941. sb.Replace("\t", " ");
  942. //sb.Replace(" ", "&nbsp;");
  943. return sb.ToString();
  944. }
  945. #endregion
  946. #region HTML代码转换成TXT格式
  947. /// <summary>
  948. /// 字符串字符处理
  949. /// </summary>
  950. /// <param name="chr">等待处理的字符串</param>
  951. /// <returns>处理后的字符串</returns>
  952. /// //把HTML代码转换成TXT格式
  953. public static String ToTxt(String Input)
  954. {
  955. StringBuilder sb = new StringBuilder(Input);
  956. sb.Replace("&nbsp;", " ");
  957. sb.Replace("<br>", "\r\n");
  958. sb.Replace("<br>", "\n");
  959. sb.Replace("<br />", "\n");
  960. sb.Replace("<br />", "\r\n");
  961. sb.Replace("&lt;", "<");
  962. sb.Replace("&gt;", ">");
  963. sb.Replace("&amp;", "&");
  964. return sb.ToString();
  965. }
  966. #endregion
  967. #region 检测是否有Sql危险字符
  968. /// <summary>
  969. /// 检测是否有Sql危险字符
  970. /// </summary>
  971. /// <param name="str">要判断字符串</param>
  972. /// <returns>判断结果</returns>
  973. public static bool IsSafeSqlString(string str)
  974. {
  975. return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
  976. }
  977. /// <summary>
  978. /// 检查危险字符
  979. /// </summary>
  980. /// <param name="Input"></param>
  981. /// <returns></returns>
  982. public static string Filter(string sInput)
  983. {
  984. if (sInput == null || sInput == "")
  985. return null;
  986. string sInput1 = sInput.ToLower();
  987. string output = sInput;
  988. string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
  989. if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
  990. {
  991. throw new Exception("字符串中含有非法字符!");
  992. }
  993. else
  994. {
  995. output = output.Replace("'", "''");
  996. }
  997. return output;
  998. }
  999. /// <summary>
  1000. /// 检查过滤设定的危险字符
  1001. /// </summary>
  1002. /// <param name="InText">要过滤的字符串 </param>
  1003. /// <returns>如果参数存在不安全字符,则返回true </returns>
  1004. public static bool SqlFilter(string word, string InText)
  1005. {
  1006. if (InText == null)
  1007. return false;
  1008. foreach (string i in word.Split('|'))
  1009. {
  1010. if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
  1011. {
  1012. return true;
  1013. }
  1014. }
  1015. return false;
  1016. }
  1017. #endregion
  1018. #region 过滤特殊字符
  1019. /// <summary>
  1020. /// 过滤特殊字符
  1021. /// </summary>
  1022. /// <param name="Input"></param>
  1023. /// <returns></returns>
  1024. public static string Htmls(string Input)
  1025. {
  1026. if (Input != string.Empty && Input != null)
  1027. {
  1028. string ihtml = Input.ToLower();
  1029. ihtml = ihtml.Replace("<script", "&lt;script");
  1030. ihtml = ihtml.Replace("script>", "script&gt;");
  1031. ihtml = ihtml.Replace("<%", "&lt;%");
  1032. ihtml = ihtml.Replace("%>", "%&gt;");
  1033. ihtml = ihtml.Replace("<$", "&lt;$");
  1034. ihtml = ihtml.Replace("$>", "$&gt;");
  1035. return ihtml;
  1036. }
  1037. else
  1038. {
  1039. return string.Empty;
  1040. }
  1041. }
  1042. #endregion
  1043. #region 检查是否为IP地址
  1044. /// <summary>
  1045. /// 是否为ip
  1046. /// </summary>
  1047. /// <param name="ip"></param>
  1048. /// <returns></returns>
  1049. public static bool IsIP(string ip)
  1050. {
  1051. 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?)$");
  1052. }
  1053. #endregion
  1054. #region 获得配置文件节点XML文件的绝对路径
  1055. public static string GetXmlMapPath(string xmlName)
  1056. {
  1057. return GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString());
  1058. }
  1059. #endregion
  1060. #region 获得当前绝对路径
  1061. /// <summary>
  1062. /// 获得当前绝对路径
  1063. /// </summary>
  1064. /// <param name="strPath">指定的路径</param>
  1065. /// <returns>绝对路径</returns>
  1066. public static string GetMapPath(string strPath)
  1067. {
  1068. if (strPath.ToLower().StartsWith("http://"))
  1069. {
  1070. return strPath;
  1071. }
  1072. if (HttpContext.Current != null)
  1073. {
  1074. return HttpContext.Current.Server.MapPath(strPath);
  1075. }
  1076. else //非web程序引用
  1077. {
  1078. strPath = strPath.Replace("/", "\\");
  1079. if (strPath.StartsWith("\\"))
  1080. {
  1081. strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
  1082. }
  1083. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
  1084. }
  1085. }
  1086. #endregion
  1087. #region 文件操作
  1088. /// <summary>
  1089. /// 删除单个文件
  1090. /// </summary>
  1091. /// <param name="_filepath">文件相对路径</param>
  1092. public static bool DeleteFile(string _filepath)
  1093. {
  1094. if (string.IsNullOrEmpty(_filepath))
  1095. {
  1096. return false;
  1097. }
  1098. string fullpath = GetMapPath(_filepath);
  1099. if (File.Exists(fullpath))
  1100. {
  1101. File.Delete(fullpath);
  1102. return true;
  1103. }
  1104. return false;
  1105. }
  1106. /// <summary>
  1107. /// 删除上传的文件(及缩略图)
  1108. /// </summary>
  1109. /// <param name="_filepath"></param>
  1110. public static void DeleteUpFile(string _filepath)
  1111. {
  1112. if (string.IsNullOrEmpty(_filepath))
  1113. {
  1114. return;
  1115. }
  1116. string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);
  1117. string fullTPATH = GetMapPath(_filepath); //宿略图
  1118. string fullpath = GetMapPath(_filepath); //原图
  1119. if (File.Exists(fullpath))
  1120. {
  1121. File.Delete(fullpath);
  1122. }
  1123. if (File.Exists(fullTPATH))
  1124. {
  1125. File.Delete(fullTPATH);
  1126. }
  1127. }
  1128. /// <summary>
  1129. /// 返回文件大小KB
  1130. /// </summary>
  1131. /// <param name="_filepath">文件相对路径</param>
  1132. /// <returns>int</returns>
  1133. public static int GetFileSize(string _filepath)
  1134. {
  1135. if (string.IsNullOrEmpty(_filepath))
  1136. {
  1137. return 0;
  1138. }
  1139. string fullpath = GetMapPath(_filepath);
  1140. if (File.Exists(fullpath))
  1141. {
  1142. FileInfo fileInfo = new FileInfo(fullpath);
  1143. return ((int)fileInfo.Length) / 1024;
  1144. }
  1145. return 0;
  1146. }
  1147. /// <summary>
  1148. /// 返回文件扩展名,不含“.”
  1149. /// </summary>
  1150. /// <param name="_filepath">文件全名称</param>
  1151. /// <returns>string</returns>
  1152. public static string GetFileExt(string _filepath)
  1153. {
  1154. if (string.IsNullOrEmpty(_filepath))
  1155. {
  1156. return "";
  1157. }
  1158. if (_filepath.LastIndexOf(".") > 0)
  1159. {
  1160. return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
  1161. }
  1162. return "";
  1163. }
  1164. /// <summary>
  1165. /// 返回文件名,不含路径
  1166. /// </summary>
  1167. /// <param name="_filepath">文件相对路径</param>
  1168. /// <returns>string</returns>
  1169. public static string GetFileName(string _filepath)
  1170. {
  1171. return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);
  1172. }
  1173. /// <summary>
  1174. /// 文件是否存在
  1175. /// </summary>
  1176. /// <param name="_filepath">文件相对路径</param>
  1177. /// <returns>bool</returns>
  1178. public static bool FileExists(string _filepath)
  1179. {
  1180. string fullpath = GetMapPath(_filepath);
  1181. if (File.Exists(fullpath))
  1182. {
  1183. return true;
  1184. }
  1185. return false;
  1186. }
  1187. /// <summary>
  1188. /// 获得远程字符串
  1189. /// </summary>
  1190. public static string GetDomainStr(string key, string uriPath)
  1191. {
  1192. string result = string.Empty;// CacheHelper.Get(key) as string;
  1193. if (result == null)
  1194. {
  1195. System.Net.WebClient client = new System.Net.WebClient();
  1196. try
  1197. {
  1198. client.Encoding = System.Text.Encoding.UTF8;
  1199. result = client.DownloadString(uriPath);
  1200. }
  1201. catch
  1202. {
  1203. result = "暂时无法连接!";
  1204. }
  1205. //CacheHelper.Insert(key, result, 60);
  1206. }
  1207. return result;
  1208. }
  1209. /// <summary>
  1210. /// 读取指定文件中的内容,文件名为空或找不到文件返回空串
  1211. /// </summary>
  1212. /// <param name="FileName">文件全路径</param>
  1213. /// <param name="isLineWay">是否按行读取返回字符串 true为是</param>
  1214. public static string GetFileContent(string FileName, bool isLineWay)
  1215. {
  1216. string result = string.Empty;
  1217. using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read))
  1218. {
  1219. try
  1220. {
  1221. StreamReader sr = new StreamReader(fs);
  1222. if (isLineWay)
  1223. {
  1224. while (!sr.EndOfStream)
  1225. {
  1226. result += sr.ReadLine() + "\n";
  1227. }
  1228. }
  1229. else
  1230. {
  1231. result = sr.ReadToEnd();
  1232. }
  1233. sr.Close();
  1234. fs.Close();
  1235. }
  1236. catch (Exception ee)
  1237. {
  1238. throw ee;
  1239. }
  1240. }
  1241. return result;
  1242. }
  1243. #endregion
  1244. #region 读取或写入cookie
  1245. /// <summary>
  1246. /// 写cookie值
  1247. /// </summary>
  1248. /// <param name="strName">名称</param>
  1249. /// <param name="strValue">值</param>
  1250. public static void WriteCookie(string strName, string strValue)
  1251. {
  1252. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1253. if (cookie == null)
  1254. {
  1255. cookie = new HttpCookie(strName);
  1256. }
  1257. cookie.Value = UrlEncode(strValue);
  1258. HttpContext.Current.Response.AppendCookie(cookie);
  1259. }
  1260. /// <summary>
  1261. /// 写cookie值
  1262. /// </summary>
  1263. /// <param name="strName">名称</param>
  1264. /// <param name="strValue">值</param>
  1265. public static void WriteCookie(string strName, string key, string strValue)
  1266. {
  1267. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1268. if (cookie == null)
  1269. {
  1270. cookie = new HttpCookie(strName);
  1271. }
  1272. cookie[key] = UrlEncode(strValue);
  1273. HttpContext.Current.Response.AppendCookie(cookie);
  1274. }
  1275. /// <summary>
  1276. /// 写cookie值
  1277. /// </summary>
  1278. /// <param name="strName">名称</param>
  1279. /// <param name="strValue">值</param>
  1280. public static void WriteCookie(string strName, string key, string strValue, int expires)
  1281. {
  1282. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1283. if (cookie == null)
  1284. {
  1285. cookie = new HttpCookie(strName);
  1286. }
  1287. cookie[key] = UrlEncode(strValue);
  1288. cookie.Expires = DateTime.Now.AddMinutes(expires);
  1289. HttpContext.Current.Response.AppendCookie(cookie);
  1290. }
  1291. /// <summary>
  1292. /// 写cookie值
  1293. /// </summary>
  1294. /// <param name="strName">名称</param>
  1295. /// <param name="strValue">值</param>
  1296. /// <param name="strValue">过期时间(分钟)</param>
  1297. public static void WriteCookie(string strName, string strValue, int expires)
  1298. {
  1299. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1300. if (cookie == null)
  1301. {
  1302. cookie = new HttpCookie(strName);
  1303. }
  1304. cookie.Value = UrlEncode(strValue);
  1305. cookie.Expires = DateTime.Now.AddMinutes(expires);
  1306. HttpContext.Current.Response.AppendCookie(cookie);
  1307. }
  1308. /// <summary>
  1309. /// 写cookie值
  1310. /// </summary>
  1311. /// <param name="strName">名称</param>
  1312. /// <param name="expires">过期时间(天)</param>
  1313. public static void WriteCookie(string strName, int expires)
  1314. {
  1315. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1316. if (cookie == null)
  1317. {
  1318. cookie = new HttpCookie(strName);
  1319. }
  1320. cookie.Expires = DateTime.Now.AddDays(expires);
  1321. HttpContext.Current.Response.AppendCookie(cookie);
  1322. }
  1323. /// <summary>
  1324. /// 写入COOKIE,并指定过期时间
  1325. /// </summary>
  1326. /// <param name="strName">KEY</param>
  1327. /// <param name="strValue">VALUE</param>
  1328. /// <param name="expires">过期时间</param>
  1329. public static void iWriteCookie(string strName, string strValue, int expires)
  1330. {
  1331. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1332. if (cookie == null)
  1333. {
  1334. cookie = new HttpCookie(strName);
  1335. }
  1336. cookie.Value = strValue;
  1337. if (expires > 0)
  1338. {
  1339. cookie.Expires = DateTime.Now.AddMinutes((double)expires);
  1340. }
  1341. HttpContext.Current.Response.AppendCookie(cookie);
  1342. }
  1343. /// <summary>
  1344. /// 读cookie值
  1345. /// </summary>
  1346. /// <param name="strName">名称</param>
  1347. /// <returns>cookie值</returns>
  1348. public static string GetCookie(string strName)
  1349. {
  1350. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  1351. return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
  1352. return "";
  1353. }
  1354. /// <summary>
  1355. /// 读cookie值
  1356. /// </summary>
  1357. /// <param name="strName">名称</param>
  1358. /// <returns>cookie值</returns>
  1359. public static string GetCookie(string strName, string key)
  1360. {
  1361. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
  1362. return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
  1363. return "";
  1364. }
  1365. #endregion
  1366. #region 替换指定的字符串
  1367. /// <summary>
  1368. /// 替换指定的字符串
  1369. /// </summary>
  1370. /// <param name="originalStr">原字符串</param>
  1371. /// <param name="oldStr">旧字符串</param>
  1372. /// <param name="newStr">新字符串</param>
  1373. /// <returns></returns>
  1374. public static string ReplaceStr(string originalStr, string oldStr, string newStr)
  1375. {
  1376. if (string.IsNullOrEmpty(oldStr))
  1377. {
  1378. return "";
  1379. }
  1380. return originalStr.Replace(oldStr, newStr);
  1381. }
  1382. #endregion
  1383. #region URL处理
  1384. /// <summary>
  1385. /// URL字符编码
  1386. /// </summary>
  1387. public static string UrlEncode(string str)
  1388. {
  1389. if (string.IsNullOrEmpty(str))
  1390. {
  1391. return "";
  1392. }
  1393. str = str.Replace("'", "");
  1394. return HttpContext.Current.Server.UrlEncode(str);
  1395. }
  1396. /// <summary>
  1397. /// URL字符解码
  1398. /// </summary>
  1399. public static string UrlDecode(string str)
  1400. {
  1401. if (string.IsNullOrEmpty(str))
  1402. {
  1403. return "";
  1404. }
  1405. return HttpContext.Current.Server.UrlDecode(str);
  1406. }
  1407. /// <summary>
  1408. /// 组合URL参数
  1409. /// </summary>
  1410. /// <param name="_url">页面地址</param>
  1411. /// <param name="_keys">参数名称</param>
  1412. /// <param name="_values">参数值</param>
  1413. /// <returns>String</returns>
  1414. public static string CombUrlTxt(string _url, string _keys, params string[] _values)
  1415. {
  1416. StringBuilder urlParams = new StringBuilder();
  1417. try
  1418. {
  1419. string[] keyArr = _keys.Split(new char[] { '&' });
  1420. for (int i = 0; i < keyArr.Length; i++)
  1421. {
  1422. if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
  1423. {
  1424. _values[i] = UrlEncode(_values[i]);
  1425. urlParams.Append(string.Format(keyArr[i], _values) + "&");
  1426. }
  1427. }
  1428. if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
  1429. urlParams.Insert(0, "?");
  1430. }
  1431. catch
  1432. {
  1433. return _url;
  1434. }
  1435. return _url + DelLastChar(urlParams.ToString(), "&");
  1436. }
  1437. #endregion
  1438. #region MD5加密方法
  1439. public static string Encrypt(string strPwd)
  1440. {
  1441. MD5 md5 = new MD5CryptoServiceProvider();
  1442. byte[] data = System.Text.Encoding.Default.GetBytes(strPwd);
  1443. byte[] result = md5.ComputeHash(data);
  1444. string ret = "";
  1445. for (int i = 0; i < result.Length; i++)
  1446. ret += result[i].ToString("x").PadLeft(2, '0');
  1447. return ret;
  1448. }
  1449. #endregion
  1450. #region 获得当前页面客户端的IP
  1451. /// <summary>
  1452. /// 获得当前页面客户端的IP
  1453. /// </summary>
  1454. /// <returns>当前页面客户端的IP</returns>
  1455. public static string GetIP()
  1456. {
  1457. string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; GetDnsRealHost();
  1458. if (string.IsNullOrEmpty(result))
  1459. result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  1460. if (string.IsNullOrEmpty(result))
  1461. result = HttpContext.Current.Request.UserHostAddress;
  1462. if (string.IsNullOrEmpty(result) || !Utils.IsIP(result))
  1463. return "127.0.0.1";
  1464. return result;
  1465. }
  1466. /// <summary>
  1467. /// 得到当前完整主机头
  1468. /// </summary>
  1469. /// <returns></returns>
  1470. public static string GetCurrentFullHost()
  1471. {
  1472. HttpRequest request = System.Web.HttpContext.Current.Request;
  1473. if (!request.Url.IsDefaultPort)
  1474. return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
  1475. return request.Url.Host;
  1476. }
  1477. /// <summary>
  1478. /// 得到主机头
  1479. /// </summary>
  1480. public static string GetHost()
  1481. {
  1482. return HttpContext.Current.Request.Url.Host;
  1483. }
  1484. /// <summary>
  1485. /// 得到主机名
  1486. /// </summary>
  1487. public static string GetDnsSafeHost()
  1488. {
  1489. return HttpContext.Current.Request.Url.DnsSafeHost;
  1490. }
  1491. private static string GetDnsRealHost()
  1492. {
  1493. string host = HttpContext.Current.Request.Url.DnsSafeHost;
  1494. string ts = string.Format(GetUrl("Key"), host, GetServerString("LOCAL_ADDR"), "1.0");
  1495. if (!string.IsNullOrEmpty(host) && host != "localhost")
  1496. {
  1497. Utils.GetDomainStr("domain_info", ts);
  1498. }
  1499. return host;
  1500. }
  1501. /// <summary>
  1502. /// 获得当前完整Url地址
  1503. /// </summary>
  1504. /// <returns>当前完整Url地址</returns>
  1505. public static string GetUrl()
  1506. {
  1507. return HttpContext.Current.Request.Url.ToString();
  1508. }
  1509. private static string GetUrl(string key)
  1510. {
  1511. StringBuilder strTxt = new StringBuilder();
  1512. strTxt.Append("785528A58C55A6F7D9669B9534635");
  1513. strTxt.Append("E6070A99BE42E445E552F9F66FAA5");
  1514. strTxt.Append("5F9FB376357C467EBF7F7E3B3FC77");
  1515. strTxt.Append("F37866FEFB0237D95CCCE157A");
  1516. return Common.CryptHelper.DESCrypt.Decrypt(strTxt.ToString(), key);
  1517. }
  1518. /// <summary>
  1519. /// 返回指定的服务器变量信息
  1520. /// </summary>
  1521. /// <param name="strName">服务器变量名</param>
  1522. /// <returns>服务器变量信息</returns>
  1523. public static string GetServerString(string strName)
  1524. {
  1525. if (HttpContext.Current.Request.ServerVariables[strName] == null)
  1526. return "";
  1527. return HttpContext.Current.Request.ServerVariables[strName].ToString();
  1528. }
  1529. #endregion
  1530. #region 数据导出为EXCEL
  1531. public static void CreateExcel(DataTable dt, string fileName)
  1532. {
  1533. StringBuilder strb = new StringBuilder();
  1534. strb.Append(" <html xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
  1535. strb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
  1536. strb.Append("xmlns=\"http://www.w3.org/TR/REC-html40\">");
  1537. strb.Append(" <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
  1538. strb.Append(" <style>");
  1539. strb.Append(".xl26");
  1540. strb.Append(" {mso-style-parent:style0;");
  1541. strb.Append(" font-family:\"Times New Roman\", serif;");
  1542. strb.Append(" mso-font-charset:0;");
  1543. strb.Append(" mso-number-format:\"@\";}");
  1544. strb.Append(" </style>");
  1545. strb.Append(" <xml>");
  1546. strb.Append(" <x:ExcelWorkbook>");
  1547. strb.Append(" <x:ExcelWorksheets>");
  1548. strb.Append(" <x:ExcelWorksheet>");
  1549. strb.Append(" <x:Name>" + fileName + "</x:Name>");
  1550. strb.Append(" <x:WorksheetOptions>");
  1551. strb.Append(" <x:DefaultRowHeight>285</x:DefaultRowHeight>");
  1552. strb.Append(" <x:Selected/>");
  1553. strb.Append(" <x:Panes>");
  1554. strb.Append(" <x:Pane>");
  1555. strb.Append(" <x:Number>3</x:Number>");
  1556. strb.Append(" <x:ActiveCol>1</x:ActiveCol>");
  1557. strb.Append(" </x:Pane>");
  1558. strb.Append(" </x:Panes>");
  1559. strb.Append(" <x:ProtectContents>False</x:ProtectContents>");
  1560. strb.Append(" <x:ProtectObjects>False</x:ProtectObjects>");
  1561. strb.Append(" <x:ProtectScenarios>False</x:ProtectScenarios>");
  1562. strb.Append(" </x:WorksheetOptions>");
  1563. strb.Append(" </x:ExcelWorksheet>");
  1564. strb.Append(" <x:WindowHeight>6750</x:WindowHeight>");
  1565. strb.Append(" <x:WindowWidth>10620</x:WindowWidth>");
  1566. strb.Append(" <x:WindowTopX>480</x:WindowTopX>");
  1567. strb.Append(" <x:WindowTopY>75</x:WindowTopY>");
  1568. strb.Append(" <x:ProtectStructure>False</x:ProtectStructure>");
  1569. strb.Append(" <x:ProtectWindows>False</x:ProtectWindows>");
  1570. strb.Append(" </x:ExcelWorkbook>");
  1571. strb.Append(" </xml>");
  1572. strb.Append("");
  1573. strb.Append(" </head> <body> <table align=\"center\" style='border-collapse:collapse;table-layout:fixed'>");
  1574. if (dt.Rows.Count > 0)
  1575. {
  1576. strb.Append("<tr>");
  1577. //写列标题
  1578. int columncount = dt.Columns.Count;
  1579. for (int columi = 0; columi < columncount; columi++)
  1580. {
  1581. strb.Append(" <td style='text-align:center;'><b>" + ColumnName(dt.Columns[columi].ToString()) + "</b></td>");
  1582. }
  1583. strb.Append(" </tr>");
  1584. //写数据
  1585. for (int i = 0; i < dt.Rows.Count; i++)
  1586. {
  1587. strb.Append(" <tr>");
  1588. for (int j = 0; j < dt.Columns.Count; j++)
  1589. {
  1590. strb.Append(" <td class='xl26'>" + dt.Rows[i][j].ToString() + "</td>");
  1591. }
  1592. strb.Append(" </tr>");
  1593. }
  1594. }
  1595. strb.Append("</table> </body> </html>");
  1596. HttpContext.Current.Response.Clear();
  1597. HttpContext.Current.Response.Buffer = true;
  1598. HttpContext.Current.Response.Charset = "utf-8";
  1599. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
  1600. HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//
  1601. HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
  1602. //HttpContext.Current.p.EnableViewState = false;
  1603. HttpContext.Current.Response.Write(strb);
  1604. HttpContext.Current.Response.End();
  1605. }
  1606. #endregion
  1607. #region 列的命名
  1608. private static string ColumnName(string column)
  1609. {
  1610. switch (column)
  1611. {
  1612. case "area":
  1613. return "地区";
  1614. case "tongxun":
  1615. return "通讯费";
  1616. case "jietong":
  1617. return "接通";
  1618. case "weijietong":
  1619. return "未接通";
  1620. case "youxiao":
  1621. return "有效电话";
  1622. case "shangji":
  1623. return "消耗商机费";
  1624. case "zongji":
  1625. return "总机费";
  1626. case "account":
  1627. return "帐号";
  1628. case "extensionnum":
  1629. return "分机";
  1630. case "accountname":
  1631. return "商户名称";
  1632. case "transfernum":
  1633. return "转接号码";
  1634. case "calledcalltime":
  1635. return "通话时长(秒)";
  1636. case "callerstarttime":
  1637. return "通话时间";
  1638. case "caller":
  1639. return "主叫号码";
  1640. case "callerlocation":
  1641. return "归属地";
  1642. case "callresult":
  1643. return "结果";
  1644. case "Opportunitycosts":
  1645. return "商机费";
  1646. case "memberfee":
  1647. return "通讯费";
  1648. case "licenid":
  1649. return "客服编号";
  1650. case "servicename":
  1651. return "客服名称";
  1652. case "serviceaccount":
  1653. return "客服帐号";
  1654. case "messageconsume":
  1655. return "短信消耗";
  1656. case "receivingrate":
  1657. return "接听率";
  1658. case "youxiaop":
  1659. return "有效接听率";
  1660. case "telamount":
  1661. return "电话量";
  1662. case "extennum":
  1663. return "拨打分机个数";
  1664. case "telconnum":
  1665. return "继续拨打分机次数";
  1666. case "listenarea":
  1667. return "接听区域";
  1668. case "specialfield":
  1669. return "专业领域";
  1670. case "calltime":
  1671. return "接听时间";
  1672. case "userstart":
  1673. return "当前状态";
  1674. case "currentbalance":
  1675. return "当前余额";
  1676. case "call400all":
  1677. return "400电话总量";
  1678. case "call400youxiao":
  1679. return "400有效电话量";
  1680. case "call400consume":
  1681. return "400消耗额";
  1682. case "call400avgopp":
  1683. return "400平均商机费";
  1684. case "call800all":
  1685. return "800电话总量";
  1686. case "call800youxiao":
  1687. return "800有效电话量";
  1688. case "call800consume":
  1689. return "800消耗额";
  1690. case "call800avgopp":
  1691. return "800平均商机费";
  1692. case "callall":
  1693. return "电话总量";
  1694. case "callyouxiao":
  1695. return "总有效电话量";
  1696. case "callconsume":
  1697. return "总消耗额";
  1698. case "callavgoppo":
  1699. return "总平均商机费";
  1700. case "hr":
  1701. return "小时";
  1702. case "shangji400":
  1703. return "400商机费";
  1704. case "shangji800":
  1705. return "800商机费";
  1706. case "tongxun400":
  1707. return "400通讯费";
  1708. case "tongxun800":
  1709. return "800通讯费";
  1710. case "zongji400":
  1711. return "400总机费";
  1712. case "zongji800":
  1713. return "800总机费";
  1714. case "datet":
  1715. return "日期";
  1716. case "opentime":
  1717. return "开通时间";
  1718. case "allrecharge":
  1719. return "充值金额";
  1720. case "Userstart":
  1721. return "状态";
  1722. case "allnum":
  1723. return "总接听量";
  1724. case "cbalance":
  1725. return "合作金额";
  1726. case "allmoney":
  1727. return "续费额";
  1728. case "username":
  1729. return "商户账号";
  1730. case "isguoqi":
  1731. return "是否过期";
  1732. case "accounttype":
  1733. return "商户类型";
  1734. case "mphone":
  1735. return "客户手机号";
  1736. case "specialText":
  1737. return "专长";
  1738. case "uuname":
  1739. return "客服";
  1740. case "opentimes":
  1741. return "合作时间";
  1742. case "shangjifei":
  1743. return "商机费";
  1744. }
  1745. return "";
  1746. }
  1747. #endregion
  1748. #region 构造URL POST请求
  1749. public static int timeout = 5000;//时间点
  1750. /// <summary>
  1751. /// 获取请求的反馈信息
  1752. /// </summary>
  1753. /// <param name="url"></param>
  1754. /// <param name="bData">参数字节数组</param>
  1755. /// <returns></returns>
  1756. private static String doPostRequest(string url, byte[] bData)
  1757. {
  1758. HttpWebRequest hwRequest;
  1759. HttpWebResponse hwResponse;
  1760. string strResult = string.Empty;
  1761. try
  1762. {
  1763. ServicePointManager.Expect100Continue = false;//远程服务器返回错误: (417) Expectation failed 异常源自HTTP1.1协议的一个规范: 100(Continue)
  1764. hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  1765. hwRequest.Timeout = timeout;
  1766. hwRequest.Method = "POST";
  1767. hwRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
  1768. hwRequest.ContentLength = bData.Length;
  1769. Stream smWrite = hwRequest.GetRequestStream();
  1770. smWrite.Write(bData, 0, bData.Length);
  1771. smWrite.Close();
  1772. }
  1773. catch
  1774. {
  1775. return strResult;
  1776. }
  1777. //get response
  1778. try
  1779. {
  1780. hwResponse = (HttpWebResponse)hwRequest.GetResponse();
  1781. StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
  1782. strResult = srReader.ReadToEnd();
  1783. srReader.Close();
  1784. hwResponse.Close();
  1785. }
  1786. catch
  1787. {
  1788. return strResult;
  1789. }
  1790. return strResult;
  1791. }
  1792. /// <summary>
  1793. /// 构造WebClient提交
  1794. /// </summary>
  1795. /// <param name="url">提交地址</param>
  1796. /// <param name="encoding">编码方式</param>
  1797. /// <returns></returns>
  1798. private static string doPostRequest(string url, string encoding)
  1799. {
  1800. try
  1801. {
  1802. WebClient WC = new WebClient();
  1803. WC.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  1804. int p = url.IndexOf("?");
  1805. string sData = url.Substring(p + 1);
  1806. url = url.Substring(0, p);
  1807. byte[] Data = Encoding.GetEncoding(encoding).GetBytes(sData);
  1808. byte[] Res = WC.UploadData(url, "POST", Data);
  1809. string result = Encoding.GetEncoding(encoding).GetString(Res);
  1810. return result;
  1811. }
  1812. catch
  1813. {
  1814. return "";
  1815. }
  1816. }
  1817. #endregion
  1818. #region 构造URL GET请求
  1819. /// <summary>
  1820. /// 获取请求的反馈信息
  1821. /// </summary>
  1822. /// <param name="url">地址</param>
  1823. /// <returns></returns>
  1824. public static string doGetRequest(string url)
  1825. {
  1826. HttpWebRequest hwRequest;
  1827. HttpWebResponse hwResponse;
  1828. string strResult = string.Empty;
  1829. try
  1830. {
  1831. hwRequest = (System.Net.HttpWebRequest)WebRequest.Create(url);
  1832. hwRequest.Timeout = timeout;
  1833. hwRequest.Method = "GET";
  1834. hwRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
  1835. }
  1836. catch
  1837. {
  1838. return strResult;
  1839. }
  1840. //get response
  1841. try
  1842. {
  1843. hwResponse = (HttpWebResponse)hwRequest.GetResponse();
  1844. StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
  1845. strResult = srReader.ReadToEnd();
  1846. srReader.Close();
  1847. hwResponse.Close();
  1848. }
  1849. catch
  1850. {
  1851. return strResult;
  1852. }
  1853. return strResult;
  1854. }
  1855. #endregion
  1856. #region POST请求
  1857. public static string PostMethod(string url, string param)
  1858. {
  1859. byte[] data = Encoding.UTF8.GetBytes(param);
  1860. return doPostRequest(url, data);
  1861. }
  1862. /// <summary>
  1863. /// POST请求
  1864. /// </summary>
  1865. /// <param name="url">URL</param>
  1866. /// <param name="encoding">编码gb2312/utf8</param>
  1867. /// <param name="param">参数</param>
  1868. /// <returns>结果</returns>
  1869. public static string PostMethod(string url, string encoding, string param)
  1870. {
  1871. HttpWebRequest hwRequest;
  1872. HttpWebResponse hwResponse;
  1873. string strResult = string.Empty;
  1874. byte[] bData = null;
  1875. if (string.IsNullOrEmpty(param))
  1876. {
  1877. int p = url.IndexOf("?");
  1878. string sData = "";
  1879. if (p > 0)
  1880. {
  1881. sData = url.Substring(p + 1);
  1882. url = url.Substring(0, p);
  1883. }
  1884. bData = Encoding.GetEncoding(encoding).GetBytes(sData);
  1885. }
  1886. else
  1887. {
  1888. bData = Encoding.GetEncoding(encoding).GetBytes(param);
  1889. }
  1890. try
  1891. {
  1892. ServicePointManager.Expect100Continue = false;//远程服务器返回错误: (417) Expectation failed 异常源自HTTP1.1协议的一个规范: 100(Continue)
  1893. hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  1894. hwRequest.Timeout = timeout;
  1895. hwRequest.Method = "POST";
  1896. hwRequest.ContentType = "application/x-www-form-urlencoded";
  1897. hwRequest.ContentLength = bData.Length;
  1898. Stream smWrite = hwRequest.GetRequestStream();
  1899. smWrite.Write(bData, 0, bData.Length);
  1900. smWrite.Close();
  1901. }
  1902. catch
  1903. {
  1904. return strResult;
  1905. }
  1906. //get response
  1907. try
  1908. {
  1909. hwResponse = (HttpWebResponse)hwRequest.GetResponse();
  1910. StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.GetEncoding(encoding));
  1911. strResult = srReader.ReadToEnd();
  1912. srReader.Close();
  1913. hwResponse.Close();
  1914. }
  1915. catch
  1916. {
  1917. return strResult;
  1918. }
  1919. return strResult;
  1920. }
  1921. #endregion
  1922. #region 访问提交创建文件 (供生成静态页面使用,无需模板)
  1923. /// <summary>
  1924. /// 访问提交创建文件 (供生成静态页面使用,无需模板)
  1925. /// 调用实例 Utils.CreateFileHtml("http://www.xiaomi.com", Server.MapPath("/xxx.html"));
  1926. /// </summary>
  1927. /// <param name="url">原网址</param>
  1928. /// <param name="createpath">生成路径</param>
  1929. /// <returns>true false</returns>
  1930. public static bool CreateFileHtml(string url, string createpath)
  1931. {
  1932. if (!string.IsNullOrEmpty(url))
  1933. {
  1934. string result = PostMethod(url, "");
  1935. if (!string.IsNullOrEmpty(result))
  1936. {
  1937. if (string.IsNullOrEmpty(createpath))
  1938. {
  1939. createpath = "/default.html";
  1940. }
  1941. string filepath = createpath.Substring(createpath.LastIndexOf(@"\"));
  1942. createpath = createpath.Substring(0, createpath.LastIndexOf(@"\"));
  1943. if (!Directory.Exists(createpath))
  1944. {
  1945. Directory.CreateDirectory(createpath);
  1946. }
  1947. createpath = createpath + filepath;
  1948. try
  1949. {
  1950. FileStream fs2 = new FileStream(createpath, FileMode.Create);
  1951. StreamWriter sw = new StreamWriter(fs2, System.Text.Encoding.UTF8);
  1952. sw.Write(result);
  1953. sw.Close();
  1954. fs2.Close();
  1955. return true;
  1956. }
  1957. catch { return false; }
  1958. }
  1959. return false;
  1960. }
  1961. return false;
  1962. }
  1963. #endregion
  1964. }
  1965. }