Encode
public static string UrlEncode(string str)
{
StringBuilder sb = new StringBuilder();
byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str);
for (int i = 0; i < byStr.Length; i++)
{
sb.Append(@"%" + Convert.ToString(byStr[i], 16));
}
return sb.ToString();
}
Encode & Decode
使用C#自带方法
HtmlEncode与HtmlDecode:转换html,转化回车和空格的功能,可以将textarea中输入的文本按照原样在html中显示。简单的理解,就是将特殊html的字符实体与字符相互转换。
参考
public static unsafe void HtmlEncode(string value, TextWriter output) {
if (value == null) {
return;
}
if (output == null) {
throw new ArgumentNullException("output");
}
int index = IndexOfHtmlEncodingChars(value, 0);
if (index == -1) {
output.Write(value);
return;
}
Debug.Assert(0 <= index && index <= value.Length, "0 <= index && index <= value.Length");
UnicodeEncodingConformance encodeConformance = HtmlEncodeConformance;
int cch = value.Length - index;
fixed (char* str = value) {
char* pch = str;
while (index-- > 0) {
output.Write(*pch++);
}
for (; cch > 0; cch--, pch++) {
char ch = *pch;
if (ch <= '>') {
switch (ch) {
case '<':
output.Write("<");
break;
case '>':
output.Write(">");
break;
case '"':
output.Write(""");
break;
case '\'':
output.Write("'");
break;
case '&':
output.Write("&");
break;
default:
output.Write(ch);
break;
}
}
else {
int valueToEncode = -1;
#if ENTITY_ENCODE_HIGH_ASCII_CHARS
if (ch >= 160 && ch < 256) {
valueToEncode = ch;
} else
#endif // ENTITY_ENCODE_HIGH_ASCII_CHARS
if (encodeConformance == UnicodeEncodingConformance.Strict && Char.IsSurrogate(ch)) {
int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(ref pch, ref cch);
if (scalarValue >= UNICODE_PLANE01_START) {
valueToEncode = scalarValue;
}
else {
ch = (char)scalarValue;
}
}
if (valueToEncode >= 0) {
output.Write("&#");
output.Write(valueToEncode.ToString(NumberFormatInfo.InvariantInfo));
output.Write(';');
}
else {
output.Write(ch);
}
}
}
}
}
//Html编码
System.Web.HttpUtility.HtmlEncode(str)
//Html解码
System.Web.HttpUtility.HtmlDecode(str)
//Url编码
System.Web.HttpUtility.UrlEncode(str)
System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.Unicode)
//Url解码
System.Web.HttpUtility.UrlDecode(str)
System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.Unicode)