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
  • 35,101
  • 14
  • 140
  • 163
  • 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

6

Try

Uri.EscapeUriString("http://www.mysite.com/my cool page")
JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
1

Try

Server.URLEncode(uri.ToString)
Julien Roncaglia
  • 16,859
  • 3
  • 57
  • 74
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).