Does C# have an equivalent to JavaScript's encodeURIComponent()?

Solution 1:

Uri.EscapeDataString or HttpUtility.UrlEncode is the correct way to escape a string meant to be part of a URL.

Take for example the string "Stack Overflow":

  • HttpUtility.UrlEncode("Stack Overflow") --> "Stack+Overflow"

  • Uri.EscapeUriString("Stack Overflow") --> "Stack%20Overflow"

  • Uri.EscapeDataString("Stack + Overflow") --> Also encodes "+" to "%2b" ---->Stack%20%2B%20%20Overflow

Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)

Solution 2:

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

You can add a reference to the System.Web assembly if it's not available in your project