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

我想使用 C # 将一个字符串变成一个 URL。这里面一定有什么东西。NET 框架,应该有帮助,对不对?

128410 次浏览

I believe you're looking for HttpServerUtility.UrlEncode.

System.Web.HttpUtility.UrlEncode(string url)

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

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

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

It replaces spaces with %20 and not with +.

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

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.

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"

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

HttpUtility.UrlDecode works for me:

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

str2 = "name=John Doe"