【发布时间】:2016-06-30 18:26:30
【问题描述】:
当我在 C# 中的 Uri 上使用 ToString() 时,我遇到了空格编码问题,它的行为似乎因输入字符串而异。
这是我的sn-p代码:
StringBuilder sb1 = new StringBuilder("root");
sb1.Append("/");
sb1.Append(System.Uri.EscapeDataString("something with spaces"));
Uri result1 = new System.Uri(sb1.ToString(), UriKind.Relative);
// result1.ToString() returns "root/something%20with%20spaces"
StringBuilder sb2 = new StringBuilder("root");
sb2.Append("/");
sb2.Append(System.Uri.EscapeDataString("something with spacés and accènts")); // "root/something%20with%20spac%C3%A9s%20and%20acc%C3%A8nts"
Uri result2 = new System.Uri(sb2.ToString(), UriKind.Relative);
// result2.ToString() returns "root/something with spacés and accènts"
我不明白。是不是因为它试图在每个输入字符串上找到编码并因为重音而找到不同的编码?
编辑
上面的代码只是我尝试在即时窗口中运行的一个例子,真正的代码 sn-p 在一个 Uri 参数的 getter 中看起来更像这样:
public Uri RelativeUri
{
get
{
List<string> partsOfUri = new List<string>();
this.getParts(this, parts);
StringBuilder sb = new StringBuilder(this.Root);
parts.Reverse();
parts.ForEach(p =>
{
sb.Append("/");
sb.Append(System.Uri.EscapeDataString(p)); // to avoid problems with '/' in parts
});
return new System.Uri(sb.ToString(), UriKind.Relative);
}
}
这些部分是可以带有斜线、重音符号、空格等的标签。在我的解决方案中的其他地方,我调用MyObject.RelativeUri.ToString(),我得到了这种奇怪的行为。
Encoding.Default 返回System.Text.SBCSCodePageEncoding
【问题讨论】: