4

我有带有非英文字符的 file:// 链接,这些字符是用 UTF-8 编码的 UrlEncoded。为了让这些链接在浏览器中工作,我必须重新编码它们。

file://development/H%C3%A5ndplukket.doc

变成

file://development/H%e5ndplukket.doc

我有以下有效的代码:

public string ReEncodeUrl(string url)
{
    Encoding enc = Encoding.GetEncoding("iso-8859-1");
    string[] parts = url.Split('/');
    for (int i = 1; i < parts.Length; i++)
    {
        parts[i] = HttpUtility.UrlDecode(parts[i]); // Decode to string
        parts[i] = HttpUtility.UrlEncode(parts[i], enc); // Re-encode to latin1
        parts[i] = parts[i].Replace('+', ' '); // Change + to [space]
    }
    return string.Join("/", parts);
}

有更清洁的方法吗?

4

3 回答 3

1

I think that's pretty clean actually. It's readable and you said it functions correctly. As long as the implementation is hidden from the consumer, I wouldn't worry about squeezing out that last improvement.

If you are doing this operation excessively (like hundreds of executions per event) I would think about taking the implementation out of UrlEncode/UrlDecode and stream them into each other to get a performance improvement there by removing the need for string split/join, but testing would have to prove that out anyway and definitely wouldn't be "clean" :-)

于 2010-01-06T02:29:41.000 回答
0

虽然我没有看到任何真正的改变它会产生影响的方法,但不应该在你的 UrlEncode 之前将 + 空格替换为 %20 吗?

于 2009-12-18T10:01:52.617 回答
0

诚然丑陋,并不是真正的改进,但可以重新编码整个事情(避免拆分/迭代/加入)然后 .Replace("%2f", "/")

我不明白想要在最终结果中保留空格的代码 - 如果它仍然有空格,你似乎最终不会得到实际编码的东西?

于 2009-12-29T09:44:34.310 回答