如何替换URL中的特殊字符?

BFr*_*ree 16 c# url encoding

这可能很简单,但我自己找不到答案:(

基本上,我想要的是,给定这个字符串:

" http://www.google.com/search?hl=en&q=c# objects"

我想要这个输出:

http://www.google.com/search?hl=en&q=c%23+objects

我确信在框架中埋藏了一些辅助类,它可以解决这个问题,但是我找不到它.

编辑:我应该补充一点,这是一个Winforms应用程序.

Wil*_*vel 15

HttpServerUtility.UrlEncode(串)

应该解决任何麻烦的人物

要使用它,您需要添加对System.Web的引用(Project Explorer>引用>添加引用> System.Web)

完成后,您可以使用它来编码要添加到查询字符串的任何项目:

System.Web.HttpUtility.UrlEncode("c# objects");
Run Code Online (Sandbox Code Playgroud)

  • 您可以仅添加对 System.Web 的引用(项目资源管理器 > 引用 > 添加引用 > System.Web),然后使用 System.Web.HttpUtility.UrlEncode("c# objects"); (2认同)

Shi*_*mar 14

如果你不想依赖System.Web这里是我在C#OAuth库中的"UrlEncode"的实现(需要正确的实现 - 即空格应使用百分比编码而不是"+"用于空格等.)

private readonly static string reservedCharacters = "!*'();:@&=+$,/?%#[]";

public static string UrlEncode(string value)
{
    if (String.IsNullOrEmpty(value))
        return String.Empty;

    var sb = new StringBuilder();

    foreach (char @char in value)
    {
        if (reservedCharacters.IndexOf(@char) == -1)
            sb.Append(@char);
        else
            sb.AppendFormat("%{0:X2}", (int)@char);
    }
    return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)

http://en.wikipedia.org/wiki/Percent-encoding参考


dth*_*her 10

@Wilfred Knievel有接受的答案,但Uri.EscapeUriString()如果你想避免对System.Web命名空间的依赖,你也可以使用.