public static string UrlEncode(byte[] bytes, int offset, int count)
{
if (bytes == null)
{
return null;
}
return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, offset, count));
}
public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count)
{
if ((bytes == null) && (count == 0))
{
return null;
}
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if ((offset < 0) || (offset > bytes.Length))
{
throw new ArgumentOutOfRangeException("offset");
}
if ((count < 0) || ((offset + count) > bytes.Length))
{
throw new ArgumentOutOfRangeException("count");
}
return UrlEncodeBytesToBytesInternal(bytes, offset, count, true);
}
private static byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
{
int num = 0;
int num2 = 0;
for (int i = 0; i < count; i++)
{
char ch = (char) bytes[offset + i];
if (ch == ' ')
{
num++;
}
else if (!IsSafe(ch))
{
num2++;
}
}
if ((!alwaysCreateReturnValue && (num == 0)) && (num2 == 0))
{
return bytes;
}
byte[] buffer = new byte[count + (num2 * 2)];
int num4 = 0;
for (int j = 0; j < count; j++)
{
byte num6 = bytes[offset + j];
char ch2 = (char) num6;
if (IsSafe(ch2))
{
buffer[num4++] = num6;
}
else if (ch2 == ' ')
{
buffer[num4++] = 0x2b;
}
else
{
buffer[num4++] = 0x25;
buffer[num4++] = (byte) IntToHex((num6 >> 4) & 15);
buffer[num4++] = (byte) IntToHex(num6 & 15);
}
}
return buffer;
}
internal static bool IsSafe(char ch)
{
if ((((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) || ((ch >= '0') && (ch <= '9')))
{
return true;
}
switch (ch)
{
case '\'':
case '(':
case ')':
case '*':
case '-':
case '.':
case '_':
case '!':
return true;
}
return false;
}
看C#实现源码,可以参考算法 HttpUtility.UrlEncode
原创mb643d15e043b20 博主文章分类:c# ©著作权
©著作权归作者所有:来自51CTO博客作者mb643d15e043b20的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
各种排序算法C#实现&比较论文(可以供java程序员参考)
各种排序算法C#实现&比较 (可以供java人员参考)算法C#实现比较程序GUI VB.
算法 java c# microsoft vb.net -
C#复习⑨(附带C#参考答案仅限参考)
XML注释、Pointer指针、Unsafe Code
C# xml 垃圾回收机制 c# 局部变量