Utilities.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. 类说明:函数自编或由网络收集整理而成.
  3. 编写人:cload
  4. 整理日期:2014-10-25
  5. */
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Text;
  10. using System.Drawing;
  11. using System.Text.RegularExpressions;
  12. using System.Web;
  13. using System.Web.Security;
  14. namespace IPADDemo.Util
  15. {
  16. public class Utilities
  17. {
  18. #region 编解码函数
  19. #region GB2312转Unicode
  20. /// <summary>
  21. /// 单个汉字转换为%AB%CD格式,如"我=%CE%D2"
  22. /// </summary>
  23. /// <param name="Source"></param>
  24. /// <returns></returns>
  25. public static string GB2Unicode(string source)
  26. {
  27. string retStr = "";
  28. string tem = "";
  29. byte[] Bytes = Encoding.GetEncoding("GB2312").GetBytes(source);
  30. for (int i = 0; i < Bytes.Length; i++)
  31. {
  32. if (Bytes[i] >= 48 && Bytes[i] <= 57 || Bytes[i] >= 65 && Bytes[i] <= 90 || Bytes[i] >= 97 && Bytes[i] <= 122)
  33. tem = ((char)(Bytes[i])).ToString();
  34. else
  35. tem = "%" + Bytes[i].ToString("X");
  36. retStr += tem;
  37. }
  38. return retStr;
  39. }
  40. #endregion
  41. #region UTF8编码
  42. /// <summary>
  43. /// 编码部分默认转为大写字母,字符编码采用默认值
  44. /// </summary>
  45. /// <param name="Source">http://www.123.com</param>
  46. /// <returns>http%3A%2F%2Fwww.123.com</returns>
  47. public static string UTF8(string Source, bool toUpper = true)
  48. {
  49. if (toUpper)
  50. {
  51. StringBuilder sb = new StringBuilder();
  52. for (int i = 0; i < Source.Length; i++)
  53. {
  54. string t = Source[i].ToString();
  55. string k = HttpUtility.UrlEncode(t, Encoding.Default);
  56. if (t == k) sb.Append(t);
  57. else sb.Append(k.ToUpper());
  58. }
  59. return sb.ToString();
  60. }
  61. else
  62. return HttpUtility.UrlEncode(Source, Encoding.Default);
  63. }
  64. public static string URL(string Source)
  65. {
  66. return HttpUtility.UrlEncode(Source);
  67. }
  68. #endregion
  69. #region %uxxxx编码
  70. public static string EncodeStr(string Source)
  71. {
  72. return HttpUtility.UrlEncodeUnicode(Source);
  73. }
  74. #endregion
  75. #region &#xx|%uxx|%xx%yy格式解码
  76. public static string DecodeStr(string Source)
  77. {
  78. string tem = Source;
  79. if (Source.Contains("&#"))
  80. {
  81. tem = "";
  82. if (Source.EndsWith(";")) Source = Source.Substring(0, Source.Length - 1);
  83. string[] tmp = Regex.Replace(Source, "&#", "").Split(';');
  84. for (int i = 0; i < tmp.Length; i++)
  85. {
  86. string t = int.Parse(tmp[i]).ToString("x4");
  87. tem += "%u" + t.Substring(t.Length - 4);
  88. }
  89. }
  90. return HttpUtility.UrlDecode(Regex.Unescape(tem));
  91. }
  92. #endregion
  93. #region MD5加密
  94. public static string MD5(string Source)
  95. {
  96. return FormsAuthentication.HashPasswordForStoringInConfigFile(Source, "MD5");
  97. }
  98. public static string GetMD5(string sDataIn)
  99. {
  100. System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  101. byte[] bytValue, bytHash;
  102. bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
  103. bytHash = md5.ComputeHash(bytValue);
  104. md5.Clear();
  105. string sTemp = "";
  106. for (int i = 0; i < bytHash.Length; i++)
  107. {
  108. sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
  109. }
  110. return sTemp.ToLower();
  111. }
  112. #endregion
  113. #endregion
  114. #region byte[]数组或16进制文本文件转图片
  115. /// <summary>
  116. /// 输入byte[]数组或16进制文本文件的全路径文本名
  117. /// </summary>
  118. /// <param name="ByteOrPath">字节数组或全路径文件名</param>
  119. /// <returns>Image图像</returns>
  120. public static Image ImageFromByte(object ByteOrPath)
  121. {
  122. try
  123. {
  124. byte[] PicBytes = null;
  125. if (ByteOrPath.GetType().Name == "String")
  126. {
  127. string fileStr = File.ReadAllText(ByteOrPath.ToString());
  128. fileStr = Regex.Replace(fileStr, "\\s+|\r\n", "");
  129. byte[] picByte = new byte[fileStr.Length / 2];
  130. for (int i = 0; i < picByte.Length; i++)
  131. {
  132. picByte[i] = Convert.ToByte("0x" + fileStr.Substring(i * 2, 2), 16);
  133. }
  134. PicBytes = picByte;
  135. }
  136. else PicBytes = (byte[])ByteOrPath;
  137. MemoryStream ms = new MemoryStream(PicBytes);
  138. ms.Position = 0;
  139. Image img = Image.FromStream(ms);
  140. ms.Close();
  141. return img;
  142. }
  143. catch
  144. {
  145. return null;
  146. }
  147. }
  148. #endregion
  149. #region Base64字符串转图片
  150. public static Image ImageFromBase64(string PathOrStr)
  151. {
  152. try
  153. {
  154. String Base64Str = "";
  155. if (PathOrStr.Contains("\\"))
  156. Base64Str = File.ReadAllText(PathOrStr);
  157. else
  158. Base64Str = PathOrStr;
  159. byte[] arr = Convert.FromBase64String(Base64Str);
  160. MemoryStream ms = new MemoryStream(arr);
  161. Bitmap bmp = new Bitmap(ms);
  162. ms.Close();
  163. return bmp;
  164. }
  165. catch
  166. {
  167. return null;
  168. }
  169. }
  170. #endregion
  171. #region Cookie简化去除重复数据
  172. #region 正则提取Cookie
  173. public static string LiteCookies(string Cookies)
  174. {
  175. try
  176. {
  177. string rStr = "";
  178. Cookies = Cookies.Replace("HttpOnly", "").Replace(";", "; ");
  179. Regex r = new Regex("(?<=,|^)(?<cookie>[^ ]+=[\\s|\"]?(?![\"]?deleted[\"]?)[^;]+)[\"]?;");
  180. Match m = r.Match(Cookies);
  181. while (m.Success)
  182. {
  183. rStr = GetCleanCookie(rStr, m.Groups["cookie"].Value);
  184. m = m.NextMatch();
  185. }
  186. return rStr;
  187. }
  188. catch
  189. {
  190. return "";
  191. }
  192. }
  193. #endregion
  194. #region 获取一次请求中的无重复Cookie
  195. private static string GetCleanCookie(string source, string inStr)
  196. {
  197. if (source != "" && inStr != "")
  198. {
  199. bool changed = false;
  200. string[] tem = source.Split(';');
  201. for (int i = 0; i < tem.Length; i++)
  202. {
  203. if (tem[i].Split('=')[0] == inStr.Split('=')[0])
  204. {
  205. source = source.Replace(tem[i], inStr);
  206. changed = true;
  207. }
  208. }
  209. if (!changed) source += ";" + inStr;
  210. return source;
  211. }
  212. else if (inStr != "") return inStr;
  213. else if (source != "") return source;
  214. else return "";
  215. }
  216. #endregion
  217. #region 合并多次请求的Cookie,去掉重复部分
  218. public static string MergerCookies(string OldCookie, string NewCookie)
  219. {
  220. if (!string.IsNullOrEmpty(OldCookie) && !string.IsNullOrEmpty(NewCookie))
  221. {
  222. if (OldCookie == NewCookie) return OldCookie;
  223. else
  224. {
  225. List<string> Old = new List<String>(OldCookie.Split(';'));
  226. List<string> New = new List<String>(NewCookie.Split(';'));
  227. foreach (string n in New)
  228. {
  229. foreach (string o in Old)
  230. {
  231. if (o == n || o.Split('=')[0] == n.Split('=')[0])
  232. {
  233. Old.Remove(o);
  234. break;
  235. }
  236. }
  237. }
  238. List<string> list = new List<string>(Old);
  239. list.AddRange(New);
  240. return string.Join(";", list.ToArray());
  241. }
  242. }
  243. else if (!string.IsNullOrEmpty(OldCookie)) return OldCookie;
  244. else if (!string.IsNullOrEmpty(NewCookie)) return NewCookie;
  245. else return "";
  246. }
  247. #endregion
  248. #endregion
  249. #region 字符串操作函数
  250. #region 过滤html标签
  251. public static string StripHTML(string stringToStrip)
  252. {
  253. stringToStrip = Regex.Replace(stringToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  254. stringToStrip = Regex.Replace(stringToStrip, "", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  255. stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  256. stringToStrip = StripHtmlXmlTags(stringToStrip);
  257. return stringToStrip;
  258. }
  259. private static string StripHtmlXmlTags(string content)
  260. {
  261. return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  262. }
  263. #endregion
  264. #region 取中间字符串
  265. public static string GetMidStr(string Source, string StartStr, string EndStr)
  266. {
  267. try
  268. {
  269. int StartPos = Source.IndexOf(StartStr, 0) + StartStr.Length;
  270. int EndPos = Source.IndexOf(EndStr, StartPos);
  271. // int s = 0;
  272. // int le=EndStr.Length;
  273. //for (int i = 0; i < Source.Length; i++)
  274. //{
  275. // var x = Source.Length - i - le;
  276. // if (Source.Substring(x, le) == EndStr)
  277. // {
  278. // s = x;
  279. // break;
  280. // }
  281. //}
  282. return Source.Substring(StartPos, EndPos - StartPos);
  283. }
  284. catch { return ""; }
  285. }
  286. public static string GetMidStr(string Source, string EndStr)
  287. {
  288. try
  289. {
  290. /* "}"125
  291. "]" 93
  292. */
  293. int s = 0;
  294. for (int i = Source.Length-1; i >= 0; i--)
  295. {
  296. if (Source.Substring(i, 1) == EndStr)
  297. {
  298. s = i;
  299. break;
  300. }
  301. }
  302. var data = Source.Substring(0, s+1);
  303. return data;
  304. }
  305. catch { return ""; }
  306. }
  307. #endregion
  308. #endregion
  309. #region 时间操作函数
  310. #region 时间戳
  311. public static string GetTime()
  312. {
  313. DateTime timeStamp = new DateTime(1970, 1, 1);
  314. long a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000;
  315. return a.ToString();
  316. }
  317. public static double GetTimestamp
  318. {
  319. get
  320. {
  321. TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
  322. return ts.TotalMilliseconds;
  323. }
  324. }
  325. #endregion
  326. #region 时间相加
  327. public static string OperationTime(string BaseTime, string AddTime, string AddType)
  328. {
  329. DateTime dt = Convert.ToDateTime(BaseTime);
  330. DateTime rt = DateTime.Now;
  331. switch (AddType)
  332. {
  333. case "年": rt = dt.AddYears(int.Parse(AddTime)); break;
  334. case "月": rt = dt.AddMonths(int.Parse(AddTime)); break;
  335. case "日": rt = dt.AddDays(double.Parse(AddTime)); break;
  336. case "时": rt = dt.AddHours(double.Parse(AddTime)); break;
  337. case "分": rt = dt.AddMinutes(double.Parse(AddTime)); break;
  338. case "秒": rt = dt.AddSeconds(double.Parse(AddTime)); break;
  339. case "毫": rt = dt.AddMilliseconds(double.Parse(AddTime)); break;
  340. }
  341. return rt.ToString();
  342. }
  343. #endregion
  344. #region 英文月份变成数字月份
  345. public static string strToNum(string Month)
  346. {
  347. string ret = "";
  348. string[] enMonth = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  349. string[] nuMonth = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
  350. for (int i = 0; i < enMonth.Length; i++)
  351. {
  352. if (Month == enMonth[i])
  353. {
  354. ret = nuMonth[i];
  355. break;
  356. }
  357. }
  358. return ret;
  359. }
  360. #endregion
  361. #endregion
  362. }
  363. }