1 /// <summary>
2 /// 随机中文码
3 /// </summary>
4 /// <returns></returns>
5 private string GetRndCh()
6 {
7 System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码页(表)
8 object[] bytes = CreateRegionCode(4);//调用函数产生4个随机中文汉字编码
9 string[] str
= new string[4];
10 System.Text.StringBuilder sb
= new System.Text.StringBuilder();
11 for (int i = 0; i < 4; i++)
12 {
13 //根据汉字编码的字节数组解码出中文汉字
14 str
[i
] = gb
.GetString((byte[])Convert
.ChangeType(bytes
[i
],
typeof(byte[])));
15 sb.Append( str[i].ToString());
16 }
17 return sb.ToString ();
18 }
19
20
21 /// <summary>
22 /// 产生随机中文汉字编码
23 /// </summary>
24 /// <param name="strlength"></param>
25 /// <returns></returns>
26 private static object[] CreateRegionCode(int strlength)
27 {
28 //定义一个字符串数组储存汉字编码的组成元素
29 string[] rBase
= new String[16] { "0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f" };
30 Random rnd
= new Random
();
31 object[] bytes
= new object[strlength
];
32
33 for (int i = 0; i < strlength; i++)
34 {
35 //区位码第1位
36 int r1 = rnd.Next(11, 14);
37 string str_r1 = rBase[r1].Trim();
38
39 //区位码第2位
40 rnd
= new Random
(r1
* unchecked((int)DateTime
.Now.Ticks) + i
);
41 int r2;
42 if (r1 == 13)
43 {
44 r2 = rnd.Next(0, 7);
45 }
46 else
47 {
48 r2 = rnd.Next(0, 16);
49 }
50 string str_r2 = rBase[r2].Trim();
51
52 //区位码第3位
53 rnd
= new Random
(r2
* unchecked((int)DateTime
.Now.Ticks) + i
);//更换随机种子
54 int r3 = rnd.Next(10, 16);
55 string str_r3 = rBase[r3].Trim();
56
57 //区位码第4位
58 rnd
= new Random
(r3
* unchecked((int)DateTime
.Now.Ticks) + i
);
59 int r4;
60 if (r3 == 10)
61 {
62 r4 = rnd.Next(1, 16);
63 }
64 else if (r3 == 15)
65 {
66 r4 = rnd.Next(0, 15);
67 }
68 else
69 {
70 r4 = rnd.Next(0, 16);
71 }
72 string str_r4 = rBase[r4].Trim();
73
74 //定义两个字节变量存储产生的随机汉字区位码
75 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
76 byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
77
78 //将两个字节变量存储在字节数组中
79 byte[] str_r
= new byte[] { byte1, byte2
};
80
81 //将产生的一个汉字的字节数组放入object数组中
82 bytes.SetValue(str_r, i);
83 }
84 return bytes;
85 }