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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/533527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:06:24  来源:igfitidea点击:

How do I replace special characters in a URL?

c#urlencoding

提问by BFree

This is probably very simple, but I simply cannot find the answer myself :(

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

Basicaly, what I want is, given this string:

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

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

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

I want this output:

我想要这个输出:

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

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

I'm sure there's some helper class somewhere buried in the Framework that takes care of that for me, but I'm having trouble finding it.

我确信框架中的某个地方有一些帮助类可以为我处理这个问题,但是我找不到它。

EDIT: I should add, that this is for a Winforms App.

编辑:我应该补充一点,这是针对 Winforms 应用程序的。

采纳答案by Wilfred Knievel

HttpServerUtility.UrlEncode(string)

HttpServerUtility.UrlEncode(string)

Should sort out any troublesome characters

应该整理出任何麻烦的字符

To use it you'll need to add a reference to System.Web (Project Explorer > References > Add reference > System.Web)

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

Once you've done that you can use it to encode any items you wish to add to the querystring:

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

System.Web.HttpUtility.UrlEncode("c# objects");

回答by dthrasher

@Wilfred Knievel has the accepted answer, but you could also use Uri.EscapeUriString()if you wanted to avoid the dependency on the System.Webnamespace.

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

回答by Shiv Kumar

If you don't want a dependency on System.Web here is an implementation of "UrlEncode" I have in my C# OAuth Library (which requires a correct implementation - namely spaces should be encoded using percent encoding rather the "+" for spaces etc.)

如果您不想依赖 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();
}

For reference http://en.wikipedia.org/wiki/Percent-encoding

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