StringExtensions.cs 25 KB

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