谁还有更简单的请留言!部分代码方便调试,未精简。
VerifyIdCard.cs
1 using System;
2 using System.Text.RegularExpressions;
3
4 namespace Hongcing
5 {
6 /// <summary>
7 /// 验证公民身份号码/身份证号码升位
8 /// </summary>
9 public static class VerifyIdCard
10 {
11 static readonly int[] iW = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
12 //static readonly char[] szVerCode ={ '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
13 static readonly string szVerCode = "10X98765432";
14
15 /// <summary>
16 /// 获取校验码
17 /// </summary>
18 /// <param name="id">17位字符串</param>
19 /// <returns>返回的校验码</returns>
20 private static char GetVerifyCode(string id)
21 {
22 if (!Regex.IsMatch(id, @"^\d{17}$"))
23 throw new ArgumentException("必须是17位数字", "id");
24
25 int iS = 0;
26 for (int i = 0, j = 0; i < id.Length && j < iW.Length; i++, j++)
27 {
28 int iA = id[i] - '0';
29 iS += iA * iW[j];
30 }
31 int iY = iS % 11;
32 return szVerCode[iY];
33 }
34
35 /// <summary>
36 /// 公民身份号码 15 位升级为 18 位
37 /// </summary>
38 /// <param name="id">15 位公民身份号码</param>
39 /// <returns>18 位公民身份号码</returns>
40 public static string Upgrade(string id)
41 {
42 if (!Regex.IsMatch(id, @"^\d{15}$"))
43 throw new ArgumentException("必须是15位数字", "id");
44
45 string tempId = id.Insert(6, "19");
46 string newId = tempId + GetVerifyCode(tempId);
47 return newId;
48 }
49
50 /// <summary>
51 /// 验证 18 位公民身份号码是否有效
52 /// </summary>
53 /// <param name="id">18 位公民身份号码</param>
54 /// <returns>有效为 true,无效为 false</returns>
55 public static bool Verify(string id)
56 {
57 if (!Regex.IsMatch(id, @"^\d{17}[0-9X]$"))
58 throw new ArgumentException("必须是18位数字或者前17位为数字最后一位为大写字母 X", "id");
59
60 string tempId = id.Substring(0, 17);
61 char oldVerifyCode = id[17];
62 char newVerifyCode = GetVerifyCode(tempId);
63 return oldVerifyCode == newVerifyCode;
64 }
65 }
66 }
67