I want to make a string into a URL using C#. There must be something in the .NET framework that should help, right?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
I found useful
System.Web.HttpUtility.UrlPathEncode(string str);
It replaces spaces with %20 and not with +.
I believe you're looking for HttpServerUtility.UrlEncode.
HttpUtility.UrlEncode Method (String)
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
orUrlEncode
(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 URLUri.EscapeDataString
for escaping any parameters in the URLThis code
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 HTMLA
tag, or used withcurl
, or encoded into a QR code, etc.The below code will replace repeating space with a single %20 character.
Example:
Input is:
Output:
Code