如何在 C# 中用 %20 替换所有空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1517586/
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-06 18:20:01  来源:igfitidea点击:

How do I replace all the spaces with %20 in C#?

c#urlurlencode

提问by Haim Bender

I want to make a string into a URL using C#. There must be something in the .NET framework that should help, right?

我想使用 C# 将字符串转换为 URL。.NET 框架中肯定有一些东西应该会有所帮助,对吧?

采纳答案by LiraNuna

I believe you're looking for HttpServerUtility.UrlEncode.

我相信您正在寻找HttpServerUtility.UrlEncode

System.Web.HttpUtility.UrlEncode(string url)

回答by George Mauer

HttpServerUtility.HtmlEncode

HttpServerUtility.HtmlEncode

From the documentation:

从文档:

String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);

But this actually encodes HTML, not URLs. Instead use UrlEncode(TestString).

但这实际上编码的是 HTML,而不是 URL。而是使用UrlEncode(TestString)

回答by Dirk Vollmar

Another way of doing this is using Uri.EscapeUriString(stringToEscape).

另一种方法是使用 Uri.EscapeUriString(stringToEscape).

回答by Gilda

I found useful System.Web.HttpUtility.UrlPathEncode(string str);

我发现有用 System.Web.HttpUtility.UrlPathEncode(string str);

It replaces spaces with %20 and not with +.

它将空格替换为 %20 而不是 +。

回答by palswim

To properly escape spaces as well as the rest of the special characters, use System.Uri.EscapeDataString(string stringToEscape).

要正确转义空格以及其他特殊字符,请使用System.Uri.EscapeDataString(string stringToEscape).

回答by nothingisnecessary

I needed to do this too, found this question from years ago but question title and text don't quite match up, and using Uri.EscapeDataStringor UrlEncode(don't use that one please!) doesn't usually make sense unless we are talking about passing URLs as parameters to other URLs.

我也需要这样做,几年前发现了这个问题,但问题标题和文本不太匹配,并且使用Uri.EscapeDataStringor UrlEncode(请不要使用那个!)通常没有意义,除非我们正在谈论通过URL 作为其他 URL 的参数。

(For example, passing a callback URL when doing open ID authentication, Azure AD, etc.)

(例如,在做开放ID认证、Azure AD等时传递回调URL)

Hoping this is more pragmatic answer to the question: I want to make a string into a URL using C#, there must be something in the .NET framework that should help, right?

希望这是对这个问题更务实的回答:我想使用 C# 将一个字符串变成一个 URL,.NET 框架中肯定有一些东西应该有帮助,对吧?

Yes- two functions are helpful for making URL strings in C#

- 两个函数有助于在 C# 中制作 URL 字符串

  • String.Formatfor formatting the URL
  • Uri.EscapeDataStringfor escaping any parameters in the URL
  • String.Format用于格式化 URL
  • Uri.EscapeDataString用于转义 URL 中的任何参数

This code

这段代码

String.Format("https://site/app/?q={0}&redirectUrl={1}", 
  Uri.EscapeDataString("search for cats"), 
  Uri.EscapeDataString("https://mysite/myapp/?state=from idp"))

produces this result

产生这个结果

https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp

https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp

Which can be safely copied and pasted into a browser's address bar, or the srcattribute of a HTML Atag, or used with curl, or encoded into a QR code, etc.

可以安全地复制粘贴到浏览器的地址栏,或srcHTMLA标签的属性中,或与 一起使用curl,或编码成二维码等。

回答by Darrelk

As commented on the approved story, the HttpServerUtility.UrlEncodemethod replaces spaces with + instead of %20. Use one of these two methods instead: Uri.EscapeUriString()or Uri.EscapeDataString()

正如对已批准故事的评论,HttpServerUtility.UrlEncode方法用 + 而不是 %20 替换空格。请改用以下两种方法之一:Uri.EscapeUriString()Uri.EscapeDataString()

Sample code:

示例代码:

HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//"https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//"https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//"https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"

//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//"https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");

//"https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"

回答by Hitesh Jain

The below code will replace repeating space with a single %20 character.

下面的代码将用单个 %20 字符替换重复空格。

Example:

例子:

Input is:

输入是:

Code by Hitesh             Jain

Output:

输出:

Code%20by%20Hitesh%20Jain

Code

代码

static void Main(string[] args)
{
    Console.WriteLine("Enter a string");
    string str = Console.ReadLine();
    string replacedStr = null;

    // This loop will repalce all repeat black space in single space
    for (int i = 0; i < str.Length - 1; i++)
    {
        if (!(Convert.ToString(str[i]) == " " &&
            Convert.ToString(str[i + 1]) == " "))
        {
            replacedStr = replacedStr + str[i];
        }
    }
    replacedStr = replacedStr + str[str.Length-1]; // Append last character
    replacedStr = replacedStr.Replace(" ", "%20");
    Console.WriteLine(replacedStr);
    Console.ReadLine();
}