88

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Haim Bender
  • 7,937
  • 10
  • 53
  • 55
  • This question title does not match the question. To replace all spaces with %20 (the title) in C# you could use `String.Replace(" ", "%20")`. If you are building an URL all you need to do is put an URL value in a string: `string url = "https://site/app/?q=cats"` But if OP was talking about passing an URL as a GET parameter as part of another URL that is something else entirely, which itself different from, say, emitting an URL into an HTML anchor tag in ASP.NET (or whatever). – nothingisnecessary Oct 05 '17 at 23:00

11 Answers11

130

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

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
58

I believe you're looking for HttpServerUtility.UrlEncode.

System.Web.HttpUtility.UrlEncode(string url)
Eregrith
  • 4,263
  • 18
  • 39
LiraNuna
  • 64,916
  • 15
  • 117
  • 140
  • 12
    I think [Uri.EscapeUriString()](https://msdn.microsoft.com/en-us/library/system.uri.escapeuristring%28v=vs.110%29.aspx) is the appropriate method if we have to be religious about it :) – Stoyan Dimov Nov 09 '15 at 10:05
  • 21
    @StoyanDimov: `EscapeUriString()` doesn't escape `&` nor `=` nor `?`, so `EscapeDataString()` does appear to be the one to use. – Doug S Nov 11 '15 at 00:11
  • 4
    Someone had edited this question to completely change the answer. We [should not use editing to change the meaning](http://stackoverflow.com/help/editing) of a particular post. – palswim Sep 16 '16 at 20:11
  • 27
    @palswim Yes, but the "accepted" answer can't be the one you reverted to: `System.Web.HttpUtility.UrlEncode` encodes space as `+` and not `%20`, so this one is totally incorrect. – Eregrith Nov 09 '16 at 16:45
  • @palswim I reverted my rollback: The accepted answer *was* indeed the ***incorrect*** one. Go figure. – Eregrith Nov 09 '16 at 16:48
  • Mine is adding `+` instead of %20... any idea why? – Si8 Apr 04 '17 at 18:13
  • 17
    Wrong answer - Don't use `UrlEncode` because it replaces spaces with `+` (instead of `%20` which the OP was specifically asking for) which is not a standard URI scheme. `decodeURI` and `decodeURIComponent` in JavaScript will not decode this properly. Use `Uri.EscapeDataString` which can be decoded properly by JavaScript for good round-trip usage of encoded data and URIs – nothingisnecessary Oct 06 '17 at 13:34
  • `which is not a standard URI scheme` < actually it is: https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 – CherryDT Jun 22 '20 at 14:54
51

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

It replaces spaces with %20 and not with +.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Gilda
  • 519
  • 4
  • 2
  • There is, at least in 4.0. System.Web.HttpUtility.UrlDecode("a%20b") yields "a b" – Abacus May 07 '13 at 21:13
  • 4
    It works but don't use this since it is for browsers. Use Uri.EscapeUriString(STRING) instead. MSDN : "Do not use; intended only for browser compatibility. Use UrlEncode." http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.urlpathencode.aspx – VRC Aug 21 '13 at 12:27
  • I found it helpful because I just wanted to encode part of the URL but still have it clickable. These did more than desired: System.Uri.EscapeDataString(url) and HttpContext.Current.Server.UrlEncode(url) – sobelito Jul 05 '16 at 15:08
  • 2
    I needed to encode spaces to %20 and not to + in order to successfully post to Twitter. UrlEncode(url) turns spaces into + and therefore was not the correct answer for my problem. – jgerman Dec 01 '16 at 17:23
27

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

palswim
  • 11,856
  • 6
  • 53
  • 77
  • 1
    If a [comment is an actual answer](http://stackoverflow.com/questions/1517586/how-do-i-replace-all-the-spaces-with-20-in-c-sharp/36462468#comment3483210_1517592), somebody needs to make that an answer for the question. – palswim Apr 06 '16 at 21:15
  • yes, this one handles space, # and %, but encode / to %2f – kite Mar 22 '17 at 16:19
19

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"
Darrel K.
  • 1,611
  • 18
  • 28
3

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.

nothingisnecessary
  • 6,099
  • 36
  • 60
  • And JavaScript equivalent would be something like `"https://site/app/?q=" + encodeURIComponent("search for cats") + "&redirectUrl=" + encodeURIComponent("https://mysite/myapp/?state=from idp")` which produces the same output. – nothingisnecessary Oct 06 '17 at 00:12
1

Use HttpServerUtility.UrlEncode

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

HttpUtility.UrlDecode works for me:

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

str2 = "name=John Doe"

mortenma71
  • 1,078
  • 2
  • 9
  • 27
-2

HttpUtility.UrlEncode Method (String)

Jacob
  • 34,255
  • 14
  • 110
  • 165
-2

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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-4

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
George Mauer
  • 117,483
  • 131
  • 382
  • 612