4

C#'s equivalent to encodeURIComponent is well-covered on SO and elsewhere, but what about encodeURI? Basically I want to encode invalid URL characters only and not reserved characters such as /, :, etc. So

"http://www.example.com/my cool page"

would be encoded to

"http://www.example.com/my%20cool%20page"

Is there something baked into .NET to do this? Or is a regex my best bet?

Community
  • 1
  • 1
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
  • 1
    (Do note the subtle differences between the *many methods* presented in the linked question.) – user2864740 Feb 10 '14 at 20:34
  • 2
    Please do not close this question. This is not a duplicate of the encodeURI**Component** question; I tried to make that distinction clear in my first sentence. – Todd Menier Feb 10 '14 at 20:43
  • There's nothing *baked into .NET*, it depends on what framework you're using. ASP.NET, .NET 4.5, Portable Library, etc... – Peter Ritchie Feb 10 '14 at 20:44

4 Answers4

7

Try

Uri.EscapeUriString("http://www.mysite.com/my cool page")
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

Try

Server.URLEncode(uri.ToString)
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
Brad Hurley
  • 81
  • 1
  • 1
1

Try this:

HttpUtility.UrlEncode(String)

For example:

var url_encoded_string = HttpUtility.UrlEncode(userInput);
cringer
  • 21
  • 2
0

You could use System.Net.WebUtility.UrlEncode(string value).