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

发布于 2024-08-06 04:11:21 字数 53 浏览 8 评论 0原文

我想使用 C# 将字符串变成 URL。 .NET 框架中一定有一些可以提供帮助的东西,对吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

眼角的笑意。 2024-08-13 04:11:21

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

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

耶耶耶 2024-08-13 04:11:21

我相信您正在寻找 HttpServerUtility.UrlEncode

System.Web.HttpUtility.UrlEncode(string url)

I believe you're looking for HttpServerUtility.UrlEncode.

System.Web.HttpUtility.UrlEncode(string url)
久随 2024-08-13 04:11:21

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

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

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

It replaces spaces with %20 and not with +.

2024-08-13 04:11:21

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

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

冷月断魂刀 2024-08-13 04:11:21

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

示例代码:

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

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "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");
//Output: "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");    
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"

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

Sample code:

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

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "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");
//Output: "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");    
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"
菊凝晚露 2024-08-13 04:11:21

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

(例如,在进行开放 ID 身份验证、Azure AD 等时传递回调 URL)

希望这是对问题的更务实的回答:我想使用 C# 将字符串制作为 URL,其中必须有一些内容.NET 框架应该会有所帮助,对吧?

- 有两个函数有助于在 C#

  • String.Format 中制作 URL 字符串以格式化 URL
  • Uri.EscapeDataString 用于转义 URL 中的任何参数

此代码

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

产生此结果

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

可以安全地复制并粘贴到浏览器的地址栏或 HTML A 标记的 src 属性中,或与 curl 一起使用code>,或编码成QR码等。

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.EscapeDataString or UrlEncode (don't use that one please!) doesn't usually make sense unless we are talking about passing URLs as parameters to other URLs.

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

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?

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

  • String.Format for formatting the URL
  • Uri.EscapeDataString for escaping any parameters in the 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

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

仙女 2024-08-13 04:11:21

HttpUtility.UrlDecode 对我有用:

var str = "name=John%20Doe";
var str2 = HttpUtility.UrlDecode(str);

str2 =“name=John Doe”

HttpUtility.UrlDecode works for me:

var str = "name=John%20Doe";
var str2 = HttpUtility.UrlDecode(str);

str2 = "name=John Doe"

听不够的曲调 2024-08-13 04:11:21

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

示例:

输入为:

Code by Hitesh             Jain

输出:

Code%20by%20Hitesh%20Jain

代码

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();
}

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

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();
}
香草可樂 2024-08-13 04:11:21

HttpServerUtility.HtmlEncode

来自文档:

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

但这实际上编码了 HTML,而不是网址。请改用UrlEncode(TestString)

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文