nwellnhof 提供的解决方案很好,但是HttpUtility.UrlEncode
以编码为参数的重载在 Windows Phone 上不可用。幸运的是,通过反编译框架程序集,很容易修改它以使用您想要的编码:
public class HttpUtilityEx
{
public static string UrlEncode(string url, Encoding encoding)
{
if (url == null)
{
return null;
}
byte[] bytes = encoding.GetBytes(url);
int num = 0;
int num1 = 0;
int length = (int)bytes.Length;
for (int i = 0; i < length; i++)
{
char chr = (char)bytes[i];
if (chr == ' ')
{
num++;
}
else if (!IsSafe(chr))
{
num1++;
}
}
if ((num != 0 ? true : num1 != 0))
{
byte[] hex = new byte[length + num1 * 2];
int num2 = 0;
for (int j = 0; j < length; j++)
{
byte num3 = bytes[j];
char chr1 = (char)num3;
if (IsSafe(chr1))
{
int num4 = num2;
num2 = num4 + 1;
hex[num4] = num3;
}
else if (chr1 != ' ')
{
int num5 = num2;
num2 = num5 + 1;
hex[num5] = 37;
int num6 = num2;
num2 = num6 + 1;
hex[num6] = (byte)IntToHex(num3 >> 4 & 15);
int num7 = num2;
num2 = num7 + 1;
hex[num7] = (byte)IntToHex(num3 & 15);
}
else
{
int num8 = num2;
num2 = num8 + 1;
hex[num8] = 43;
}
}
bytes = hex;
}
return encoding.GetString(bytes, 0, (int)bytes.Length);
}
private static bool IsSafe(char ch)
{
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
{
return true;
}
char chr = ch;
if (chr != '!')
{
switch (chr)
{
case '\'':
case '(':
case ')':
case '*':
case '-':
case '.':
{
break;
}
case '+':
case ',':
{
return false;
}
default:
{
if (chr != '\u005F')
{
return false;
}
else
{
break;
}
}
}
}
return true;
}
internal static char IntToHex(int n)
{
if (n <= 9)
{
return (char)(n + 48);
}
return (char)(n - 10 + 97);
}
}
从那里,您只需要像对 HttpUtility 一样调用它:
var result = HttpUtilityEx.UrlEncode("ä", Encoding.GetEncoding("ISO-8859-1"));