StringExtensions.cs 24 KB

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