StringExtensions.cs 24 KB

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