StringExtensions.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. using DnsClient;
  2. using Masuit.Tools.DateTimeExt;
  3. using Masuit.Tools.Strings;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Numerics;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace Masuit.Tools
  17. {
  18. public static partial class StringExtensions
  19. {
  20. public static string Join(this IEnumerable<string> strs, string separate = ", ") => string.Join(separate, strs);
  21. /// <summary>
  22. /// 字符串转时间
  23. /// </summary>
  24. /// <param name="value"></param>
  25. /// <returns></returns>
  26. public static DateTime ToDateTime(this string value)
  27. {
  28. DateTime.TryParse(value, out var result);
  29. return result;
  30. }
  31. /// <summary>
  32. /// 字符串转Guid
  33. /// </summary>
  34. /// <param name="s"></param>
  35. /// <returns></returns>
  36. public static Guid ToGuid(this string s)
  37. {
  38. return Guid.Parse(s);
  39. }
  40. /// <summary>
  41. /// 根据正则替换
  42. /// </summary>
  43. /// <param name="input"></param>
  44. /// <param name="regex">正则表达式</param>
  45. /// <param name="replacement">新内容</param>
  46. /// <returns></returns>
  47. public static string Replace(this string input, Regex regex, string replacement)
  48. {
  49. return regex.Replace(input, replacement);
  50. }
  51. /// <summary>
  52. /// 生成唯一短字符串
  53. /// </summary>
  54. /// <param name="str"></param>
  55. /// <param name="chars">可用字符数数量,0-9,a-z,A-Z</param>
  56. /// <returns></returns>
  57. public static string CreateShortToken(this string str, byte chars = 36)
  58. {
  59. var nf = new NumberFormater(chars);
  60. return nf.ToString((DateTime.Now.Ticks - 630822816000000000) * 100 + Stopwatch.GetTimestamp() % 100);
  61. }
  62. /// <summary>
  63. /// 任意进制转十进制
  64. /// </summary>
  65. /// <param name="str"></param>
  66. /// <param name="base">进制</param>
  67. /// <returns></returns>
  68. public static long FromBinary(this string str, byte @base)
  69. {
  70. var nf = new NumberFormater(@base);
  71. return nf.FromString(str);
  72. }
  73. /// <summary>
  74. /// 任意进制转大数十进制
  75. /// </summary>
  76. /// <param name="str"></param>
  77. /// <param name="base">进制</param>
  78. /// <returns></returns>
  79. public static BigInteger FromBinaryBig(this string str, byte @base)
  80. {
  81. var nf = new NumberFormater(@base);
  82. return nf.FromStringBig(str);
  83. }
  84. #region 检测字符串中是否包含列表中的关键词
  85. /// <summary>
  86. /// 检测字符串中是否包含列表中的关键词
  87. /// </summary>
  88. /// <param name="s">源字符串</param>
  89. /// <param name="keys">关键词列表</param>
  90. /// <param name="ignoreCase">忽略大小写</param>
  91. /// <returns></returns>
  92. public static bool Contains(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  93. {
  94. if (!keys.Any() || string.IsNullOrEmpty(s))
  95. {
  96. return false;
  97. }
  98. if (ignoreCase)
  99. {
  100. return Regex.IsMatch(s, string.Join("|", keys.Select(Regex.Escape)), RegexOptions.IgnoreCase);
  101. }
  102. return Regex.IsMatch(s, string.Join("|", keys.Select(Regex.Escape)));
  103. }
  104. /// <summary>
  105. /// 检测字符串中是否包含列表中的关键词
  106. /// </summary>
  107. /// <param name="s">源字符串</param>
  108. /// <param name="regex">关键词列表</param>
  109. /// <param name="ignoreCase">忽略大小写</param>
  110. /// <returns></returns>
  111. public static bool RegexMatch(this string s, string regex, bool ignoreCase = true)
  112. {
  113. if (string.IsNullOrEmpty(regex) || string.IsNullOrEmpty(s))
  114. {
  115. return false;
  116. }
  117. if (ignoreCase)
  118. {
  119. return Regex.IsMatch(s, regex, RegexOptions.IgnoreCase);
  120. }
  121. return Regex.IsMatch(s, regex);
  122. }
  123. /// <summary>
  124. /// 检测字符串中是否包含列表中的关键词
  125. /// </summary>
  126. /// <param name="s">源字符串</param>
  127. /// <param name="regex">关键词列表</param>
  128. /// <returns></returns>
  129. public static bool RegexMatch(this string s, Regex regex) => !string.IsNullOrEmpty(s) && regex.IsMatch(s);
  130. /// <summary>
  131. /// 判断是否包含符号
  132. /// </summary>
  133. /// <param name="str"></param>
  134. /// <param name="symbols"></param>
  135. /// <returns></returns>
  136. public static bool ContainsSymbol(this string str, params string[] symbols)
  137. {
  138. return str switch
  139. {
  140. null => false,
  141. "" => false,
  142. _ => symbols.Any(str.Contains)
  143. };
  144. }
  145. #endregion 检测字符串中是否包含列表中的关键词
  146. /// <summary>
  147. /// 判断字符串是否为空或""
  148. /// </summary>
  149. /// <param name="s"></param>
  150. /// <returns></returns>
  151. public static bool IsNullOrEmpty(this string s)
  152. {
  153. return string.IsNullOrEmpty(s);
  154. }
  155. /// <summary>
  156. /// 字符串掩码
  157. /// </summary>
  158. /// <param name="s">字符串</param>
  159. /// <param name="mask">掩码符</param>
  160. /// <returns></returns>
  161. public static string Mask(this string s, char mask = '*')
  162. {
  163. if (string.IsNullOrWhiteSpace(s?.Trim()))
  164. {
  165. return s;
  166. }
  167. s = s.Trim();
  168. string masks = mask.ToString().PadLeft(4, mask);
  169. return s.Length switch
  170. {
  171. >= 11 => Regex.Replace(s, "(.{3}).*(.{4})", $"$1{masks}$2"),
  172. 10 => Regex.Replace(s, "(.{3}).*(.{3})", $"$1{masks}$2"),
  173. 9 => Regex.Replace(s, "(.{2}).*(.{3})", $"$1{masks}$2"),
  174. 8 => Regex.Replace(s, "(.{2}).*(.{2})", $"$1{masks}$2"),
  175. 7 => Regex.Replace(s, "(.{1}).*(.{2})", $"$1{masks}$2"),
  176. 6 => Regex.Replace(s, "(.{1}).*(.{1})", $"$1{masks}$2"),
  177. _ => Regex.Replace(s, "(.{1}).*", $"$1{masks}")
  178. };
  179. }
  180. #region Email
  181. /// <summary>
  182. /// 匹配Email
  183. /// </summary>
  184. /// <param name="s">源字符串</param>
  185. /// <param name="valid">是否验证有效性</param>
  186. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  187. public static (bool isMatch, Match match) MatchEmail(this string s, bool valid = false)
  188. {
  189. if (string.IsNullOrEmpty(s) || s.Length < 7)
  190. {
  191. return (false, null);
  192. }
  193. var match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  194. var isMatch = match.Success;
  195. if (isMatch && valid)
  196. {
  197. var nslookup = new LookupClient();
  198. var task = nslookup.Query(s.Split('@')[1], QueryType.MX).Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  199. {
  200. if (t.IsCanceled || t.IsFaulted)
  201. {
  202. return new[] { IPAddress.Loopback };
  203. }
  204. return t.Result;
  205. }));
  206. isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  207. }
  208. return (isMatch, match);
  209. }
  210. /// <summary>
  211. /// 匹配Email
  212. /// </summary>
  213. /// <param name="s">源字符串</param>
  214. /// <param name="valid">是否验证有效性</param>
  215. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  216. public static async Task<(bool isMatch, Match match)> MatchEmailAsync(this string s, bool valid = false)
  217. {
  218. if (string.IsNullOrEmpty(s) || s.Length < 7)
  219. {
  220. return (false, null);
  221. }
  222. var match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  223. var isMatch = match.Success;
  224. if (isMatch && valid)
  225. {
  226. var nslookup = new LookupClient();
  227. using var cts = new CancellationTokenSource(100);
  228. var query = await nslookup.QueryAsync(s.Split('@')[1], QueryType.MX, cancellationToken: cts.Token);
  229. var result = await query.Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  230. {
  231. if (t.IsCanceled || t.IsFaulted)
  232. {
  233. return new[] { IPAddress.Loopback };
  234. }
  235. return t.Result;
  236. }));
  237. isMatch = result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  238. }
  239. return (isMatch, match);
  240. }
  241. /// <summary>
  242. /// 邮箱掩码
  243. /// </summary>
  244. /// <param name="s">邮箱</param>
  245. /// <param name="mask">掩码</param>
  246. /// <returns></returns>
  247. public static string MaskEmail(this string s, char mask = '*')
  248. {
  249. var index = s.LastIndexOf("@");
  250. var oldValue = s.Substring(0, index);
  251. return !MatchEmail(s).isMatch ? s : s.Replace(oldValue, Mask(oldValue, mask));
  252. }
  253. #endregion Email
  254. #region 匹配完整的URL
  255. /// <summary>
  256. /// 匹配完整格式的URL
  257. /// </summary>
  258. /// <param name="s">源字符串</param>
  259. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  260. /// <returns>匹配对象</returns>
  261. public static Uri MatchUrl(this string s, out bool isMatch)
  262. {
  263. try
  264. {
  265. var uri = new Uri(s);
  266. isMatch = Dns.GetHostAddresses(uri.Host).Any(ip => !ip.IsPrivateIP());
  267. return uri;
  268. }
  269. catch
  270. {
  271. isMatch = false;
  272. return null;
  273. }
  274. }
  275. /// <summary>
  276. /// 匹配完整格式的URL
  277. /// </summary>
  278. /// <param name="s">源字符串</param>
  279. /// <returns>是否匹配成功</returns>
  280. public static bool MatchUrl(this string s)
  281. {
  282. MatchUrl(s, out var isMatch);
  283. return isMatch;
  284. }
  285. #endregion 匹配完整的URL
  286. #region 权威校验身份证号码
  287. /// <summary>
  288. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  289. /// </summary>
  290. /// <param name="s">源字符串</param>
  291. /// <returns>是否匹配成功</returns>
  292. public static bool MatchIdentifyCard(this string s)
  293. {
  294. return s.Length switch
  295. {
  296. 18 => CheckChinaID18(s),
  297. 15 => CheckChinaID15(s),
  298. _ => false
  299. };
  300. }
  301. private static readonly string[] ChinaIDProvinceCodes = {
  302. "11", "12", "13", "14", "15",
  303. "21", "22", "23",
  304. "31", "32", "33", "34", "35", "36", "37",
  305. "41", "42", "43", "44", "45", "46",
  306. "50", "51", "52", "53", "54",
  307. "61", "62", "63", "64", "65",
  308. "71",
  309. "81", "82",
  310. "91"
  311. };
  312. private static bool CheckChinaID18(string ID)
  313. {
  314. ID = ID.ToUpper();
  315. Match m = Regex.Match(ID, @"\d{17}[\dX]", RegexOptions.IgnoreCase);
  316. if (!m.Success)
  317. {
  318. return false;
  319. }
  320. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  321. {
  322. return false;
  323. }
  324. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  325. if (!DateTime.TryParseExact(ID.Substring(6, 8), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  326. {
  327. return false;
  328. }
  329. if (!birthday.In(new DateTime(1800, 1, 1), DateTime.Today))
  330. {
  331. return false;
  332. }
  333. int[] factors = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
  334. int sum = 0;
  335. for (int i = 0; i < 17; i++)
  336. {
  337. sum += (ID[i] - '0') * factors[i];
  338. }
  339. int n = (12 - sum % 11) % 11;
  340. return n < 10 ? ID[17] - '0' == n : ID[17].Equals('X');
  341. }
  342. private static bool CheckChinaID15(string ID)
  343. {
  344. Match m = Regex.Match(ID, @"\d{15}", RegexOptions.IgnoreCase);
  345. if (!m.Success)
  346. {
  347. return false;
  348. }
  349. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  350. {
  351. return false;
  352. }
  353. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  354. if (!DateTime.TryParseExact("19" + ID.Substring(6, 6), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  355. {
  356. return false;
  357. }
  358. return birthday.In(new DateTime(1800, 1, 1), new DateTime(2000, 1, 1));
  359. }
  360. #endregion 权威校验身份证号码
  361. #region IP地址
  362. /// <summary>
  363. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  364. /// </summary>
  365. /// <param name="s">源字符串</param>
  366. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  367. /// <returns>匹配对象</returns>
  368. public static IPAddress MatchInetAddress(this string s, out bool isMatch)
  369. {
  370. isMatch = IPAddress.TryParse(s, out var ip);
  371. return ip;
  372. }
  373. /// <summary>
  374. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  375. /// </summary>
  376. /// <param name="s">源字符串</param>
  377. /// <returns>是否匹配成功</returns>
  378. public static bool MatchInetAddress(this string s)
  379. {
  380. MatchInetAddress(s, out var success);
  381. return success;
  382. }
  383. /// <summary>
  384. /// IP地址转换成数字
  385. /// </summary>
  386. /// <param name="addr">IP地址</param>
  387. /// <returns>数字,输入无效IP地址返回0</returns>
  388. public static uint IPToID(this string addr)
  389. {
  390. if (!IPAddress.TryParse(addr, out var ip))
  391. {
  392. return 0;
  393. }
  394. byte[] bInt = ip.GetAddressBytes();
  395. if (BitConverter.IsLittleEndian)
  396. {
  397. Array.Reverse(bInt);
  398. }
  399. return BitConverter.ToUInt32(bInt, 0);
  400. }
  401. /// <summary>
  402. /// 判断IP是否是私有地址
  403. /// </summary>
  404. /// <param name="ip"></param>
  405. /// <returns></returns>
  406. public static bool IsPrivateIP(this string ip)
  407. {
  408. var address = MatchInetAddress(ip, out var b);
  409. return b && address.IsPrivateIP();
  410. }
  411. /// <summary>
  412. /// 判断IP地址在不在某个IP地址段
  413. /// </summary>
  414. /// <param name="input">需要判断的IP地址</param>
  415. /// <param name="begin">起始地址</param>
  416. /// <param name="ends">结束地址</param>
  417. /// <returns></returns>
  418. public static bool IpAddressInRange(this string input, string begin, string ends)
  419. {
  420. uint current = input.IPToID();
  421. return current >= begin.IPToID() && current <= ends.IPToID();
  422. }
  423. #endregion IP地址
  424. #region 校验手机号码的正确性
  425. /// <summary>
  426. /// 匹配手机号码
  427. /// </summary>
  428. /// <param name="s">源字符串</param>
  429. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  430. /// <returns>匹配对象</returns>
  431. public static Match MatchPhoneNumber(this string s, out bool isMatch)
  432. {
  433. if (string.IsNullOrEmpty(s))
  434. {
  435. isMatch = false;
  436. return null;
  437. }
  438. Match match = Regex.Match(s, @"^((1[3,5,6,8][0-9])|(14[5,7])|(17[0,1,3,6,7,8])|(19[8,9]))\d{8}$");
  439. isMatch = match.Success;
  440. return isMatch ? match : null;
  441. }
  442. /// <summary>
  443. /// 匹配手机号码
  444. /// </summary>
  445. /// <param name="s">源字符串</param>
  446. /// <returns>是否匹配成功</returns>
  447. public static bool MatchPhoneNumber(this string s)
  448. {
  449. MatchPhoneNumber(s, out bool success);
  450. return success;
  451. }
  452. #endregion 校验手机号码的正确性
  453. #region Url
  454. /// <summary>
  455. /// 判断url是否是外部地址
  456. /// </summary>
  457. /// <param name="url"></param>
  458. /// <returns></returns>
  459. public static bool IsExternalAddress(this string url)
  460. {
  461. var uri = new Uri(url);
  462. switch (uri.HostNameType)
  463. {
  464. case UriHostNameType.Dns:
  465. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  466. if (ipHostEntry.AddressList.Where(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork).Any(ipAddress => !ipAddress.IsPrivateIP()))
  467. {
  468. return true;
  469. }
  470. break;
  471. case UriHostNameType.IPv4:
  472. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  473. }
  474. return false;
  475. }
  476. #endregion Url
  477. /// <summary>
  478. /// 转换成字节数组
  479. /// </summary>
  480. /// <param name="this"></param>
  481. /// <returns></returns>
  482. public static byte[] ToByteArray(this string @this)
  483. {
  484. return Encoding.ASCII.GetBytes(@this);
  485. }
  486. #region Crc32
  487. /// <summary>
  488. /// 获取字符串crc32签名
  489. /// </summary>
  490. /// <param name="s"></param>
  491. /// <returns></returns>
  492. public static string Crc32(this string s)
  493. {
  494. return string.Join(string.Empty, new Security.Crc32().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  495. }
  496. /// <summary>
  497. /// 获取字符串crc64签名
  498. /// </summary>
  499. /// <param name="s"></param>
  500. /// <returns></returns>
  501. public static string Crc64(this string s)
  502. {
  503. return string.Join(string.Empty, new Security.Crc64().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  504. }
  505. #endregion Crc32
  506. #region 权威校验中国专利申请号/专利号
  507. /// <summary>
  508. /// 中国专利申请号(授权以后就是专利号)由两种组成
  509. /// 2003年9月30号以前的9位(不带校验位是8号),校验位之前可能还会有一个点,例如:00262311, 002623110 或 00262311.0
  510. /// 2003年10月1号以后的13位(不带校验位是12号),校验位之前可能还会有一个点,例如:200410018477, 2004100184779 或200410018477.9
  511. /// http://www.sipo.gov.cn/docs/pub/old/wxfw/zlwxxxggfw/hlwzljsxt/hlwzljsxtsyzn/201507/P020150713610193194682.pdf
  512. /// 上面的文档中均不包括校验算法,但是下面的校验算法没有问题
  513. /// </summary>
  514. /// <param name="patnum">源字符串</param>
  515. /// <returns>是否匹配成功</returns>
  516. public static bool MatchCNPatentNumber(this string patnum)
  517. {
  518. Regex patnumWithCheckbitPattern = new Regex(@"^
  519. (?<!\d)
  520. (?<patentnum>
  521. (?<basenum>
  522. (?<year>(?<old>8[5-9]|9[0-9]|0[0-3])|(?<new>[2-9]\d{3}))
  523. (?<sn>
  524. (?<patenttype>[12389])
  525. (?(old)\d{5}|(?(new)\d{7}))
  526. )
  527. )
  528. (?:
  529. \.?
  530. (?<checkbit>[0-9X])
  531. )?
  532. )
  533. (?!\d)
  534. $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline);
  535. Match m = patnumWithCheckbitPattern.Match(patnum);
  536. if (!m.Success)
  537. {
  538. return false;
  539. }
  540. bool isPatnumTrue = true;
  541. patnum = patnum.ToUpper().Replace(".", "");
  542. if (patnum.Length == 9 || patnum.Length == 8)
  543. {
  544. byte[] factors8 = new byte[8] { 2, 3, 4, 5, 6, 7, 8, 9 };
  545. int year = Convert.ToUInt16(patnum.Substring(0, 2));
  546. year += (year >= 85) ? (ushort)1900u : (ushort)2000u;
  547. if (year >= 1985 || year <= 2003)
  548. {
  549. int sum = 0;
  550. for (byte i = 0; i < 8; i++)
  551. {
  552. sum += factors8[i] * (patnum[i] - '0');
  553. }
  554. char checkbit = "0123456789X"[sum % 11];
  555. if (patnum.Length == 9)
  556. {
  557. if (checkbit != patnum[8])
  558. {
  559. isPatnumTrue = false;
  560. }
  561. }
  562. else
  563. {
  564. patnum += checkbit;
  565. }
  566. }
  567. else
  568. {
  569. isPatnumTrue = false;
  570. }
  571. }
  572. else if (patnum.Length == 13 || patnum.Length == 12)
  573. {
  574. byte[] factors12 = new byte[12] { 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5 };
  575. int year = Convert.ToUInt16(patnum.Substring(0, 4));
  576. if (year >= 2003 && year <= DateTime.Now.Year)
  577. {
  578. int sum = 0;
  579. for (byte i = 0; i < 12; i++)
  580. {
  581. sum += factors12[i] * (patnum[i] - '0');
  582. }
  583. char checkbit = "0123456789X"[sum % 11];
  584. if (patnum.Length == 13)
  585. {
  586. if (checkbit != patnum[12])
  587. {
  588. isPatnumTrue = false;
  589. }
  590. }
  591. else
  592. {
  593. patnum += checkbit;
  594. }
  595. }
  596. else
  597. {
  598. isPatnumTrue = false;
  599. }
  600. }
  601. else
  602. {
  603. isPatnumTrue = false;
  604. }
  605. return isPatnumTrue;
  606. }
  607. /// <summary>
  608. /// 取字符串前{length}个字
  609. /// </summary>
  610. /// <param name="s"></param>
  611. /// <param name="length"></param>
  612. /// <returns></returns>
  613. public static string Take(this string s, int length)
  614. {
  615. return s.Length > length ? s.Substring(0, length) : s;
  616. }
  617. }
  618. #endregion
  619. }