1 public static void ConvertURLGBKEnCode()
2 {
3 string str2 = "赟俶鎮臨釵阁紅昇號瀍業區號鋕發廠劉東區灣業區實業蘭創黃鐰甪恆";
4
5 string str = string.Empty;
6 string urlEnCodeStr = string.Empty;
7 Regex reg = new Regex(@"[\u4e00-\u9fa5]");//正则表达式
8 StringBuilder sb1 = new StringBuilder();
9 for (int i = 0; i <= str2.Length - 1; i++)
10 {
11 string tempStr = str2.ToString();
12 urlEnCodeStr = System.Web.HttpUtility.UrlEncode(tempStr, Encoding.GetEncoding("GBK"));
13
14 // 如果是汉子的话,将URL编码过后再进行16进制转换
15 if (reg.IsMatch(tempStr))
16 {
17 // 判断转码过后的字符,如果只有4位的话,代表最后一个字符需要转换成16进制行拼接
18 if (urlEnCodeStr.Length <= 4)
19 {
20 StringBuilder sb = new StringBuilder();
21 string firstStr = urlEnCodeStr.Substring(0, 3);
22 string LastStr = urlEnCodeStr.Substring(3, 1);
23 sb.Append(firstStr + "%");
24 byte[] targetData = Encoding.GetEncoding("GBK").GetBytes(LastStr);
25 for (int j = 0; j < targetData.Length; j++)
26 {
27 sb.Append(targetData[j].ToString("x2"));
28 }
29 sb1.Append(sb.ToString());
30 }
31 else
32 {
33 sb1.Append(urlEnCodeStr);
34 }
35 }
36 else
37 {
38 sb1.Append(urlEnCodeStr);
39 }
40 }
41
42 Console.WriteLine(sb1.ToString());
43
44 Console.ReadLine();
45 }