一切福田,不離方寸,從心而覓,感無不通。

C#的Escape和Unescape

基于C#EscapeUnescape实现

//在C#后台实现JavaScript的函数escape()的字符串转换
//些方法支持汉字
private string escape(string s)
{
StringBuilder sb = new StringBuilder();
byte[] byteArr = System.Text.Encoding.Unicode.GetBytes(s);

for (int i = 0; i < byteArr.Length; i += 2)
{
sb.Append("%u");
sb.Append(byteArr[i + 1].ToString("X2"));//把字节转换为十六进制的字符串表现形式

sb.Append(byteArr[i].ToString("X2"));
}
return sb.ToString();

}
//把JavaScript的escape()转换过去的字符串解释回来
//些方法支持汉字
private string unescape(string s)
{

string str = s.Remove(0, 2);//删除最前面两个"%u"
string[] strArr = str.Split(new string[]{"%u"}, StringSplitOptions.None);//以子字符串"%u"分隔
byte[] byteArr = new byte[strArr.Length * 2];
for (int i = 0,j=0; i < strArr.Length;i++,j+=2)
{
byteArr[j + 1] = Convert.ToByte(strArr[i].Substring(0,2), 16); //把十六进制形式的字串符串转换为二进制字节
byteArr[j ] = Convert.ToByte(strArr[i].Substring(2, 2), 16);
}
str = System.Text.Encoding.Unicode.GetString(byteArr); //把字节转为unicode编码
return str;

}

 

下面的为不支持汉字的转换:

public static string Escape(string str)
{
if (str == null)
returnString.Empty;

StringBuilder sb = newStringBuilder();
int len = str.Length;

for (int i = 0; i <len; i++)
{
char c = str[i];

//everything other than the optionally escaped chars _must_ be escaped
if (Char.IsLetterOrDigit(c) || c == '-' || c == '_’|| c == '/' || c == '\\' || c == '.')
sb.Append(c);
else
sb.Append(Uri.HexEscape(c));
}

return sb.ToString();
}

public static string UnEscape(string str)
{
if (str == null)
returnString.Empty;

StringBuilder sb = newStringBuilder();
int len = str.Length;
int i = 0;
while (i != len)
{
if (Uri.IsHexEncoding(str, i))
sb.Append(Uri.HexUnescape(str, ref i));
else
sb.Append(str[i++]);
}

return sb.ToString();
}

FROM URL: http://hi.baidu.com/yimeng3025/item/5b37ed983cc371cdb62531ac