
Code
1
瀛楃澶勭悊#region
2
public string UrlEncode(string str)
3
{
4
if (str == null)
5
{
6
return null;
7
}
8
return UrlEncode(str, Encoding.UTF8);
9
}
10
public string UrlEncode(string str, Encoding e)
11
{
12
if (str == null)
13
{
14
return null;
15
}
16
byte[] by = this.UrlEncodeToBytes(str, e);
17
18
return Encoding.ASCII.GetString(by, 0, by.Length);
19
}
20
public byte[] UrlEncodeToBytes(string str, Encoding e)
21
{
22
if (str == null)
23
{
24
return null;
25
}
26
byte[] buffer1 = e.GetBytes(str);
27
return UrlEncodeBytesToBytesInternal(buffer1, 0, buffer1.Length, false);
28
}
29
30
private byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
31
{
32
int num1 = 0;
33
int num2 = 0;
34
for (int num3 = 0; num3 < count; num3++)
35
{
36
char ch1 = (char)bytes[offset + num3];
37
if (ch1 == ' ')
38
{
39
num1++;
40
}
41
else if (!IsSafe(ch1))
42
{
43
num2++;
44
}
45
}
46
if ((!alwaysCreateReturnValue && (num1 == 0)) && (num2 == 0))
47
{
48
return bytes;
49
}
50
byte[] buffer1 = new byte[count + (num2 * 2)];
51
int num4 = 0;
52
for (int num5 = 0; num5 < count; num5++)
53
{
54
byte num6 = bytes[offset + num5];
55
char ch2 = (char)num6;
56
if (IsSafe(ch2))
57
{
58
buffer1[num4++] = num6;
59
}
60
else if (ch2 == ' ')
61
{
62
buffer1[num4++] = 0x2b;
63
}
64
else
65
{
66
buffer1[num4++] = 0x25;
67
buffer1[num4++] = (byte)IntToHex((num6 >> 4) & 15);
68
buffer1[num4++] = (byte)IntToHex(num6 & 15);
69
}
70
}
71
return buffer1;
72
}
73
private bool IsSafe(char ch)
74
{
75
if ((((ch < 'a') || (ch > 'z')) && ((ch < 'A') || (ch > 'Z'))) && ((ch < '0') || (ch > '9')))
76
{
77
char ch1 = ch;
78
switch (ch1)
79
{
80
case '\'':
81
case '(':
82
case ')':
83
case '*':
84
case '-':
85
case '.':
86
case '!':
87
{
88
break;
89
}
90
case '+':
91
case ',':
92
{
93
goto Label_0057;
94
}
95
default:
96
{
97
if (ch1 != '_')
98
{
99
goto Label_0057;
100
}
101
break;
102
}
103
}
104
}
105
return true;
106
Label_0057:
107
return false;
108
}
109
110
private char IntToHex(int n)
111
{
112
if (n <= 9)
113
{
114
return (char)((ushort)(n + 0x30));
115
}
116
return (char)((ushort)((n - 10) + 0x61));
117
}
118
119
120
#endregion
可能在wince编程中涉及URL的话,这几个方法应该派的上用场