160

In JavaScript:

encodeURIComponent("©√") == "%C2%A9%E2%88%9A"

Is there an equivalent for C# applications? For escaping HTML characters I used:

txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]",
    m => @"&#" + ((int)m.Value[0]).ToString() + ";");

But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:

txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]",
    m => @"%" + String.Format("{0:x}", ((int)m.Value[0])));

Returns "%a9%221a" for "©√" instead of "%C2%A9%E2%88%9A". It looks like I need to split the string up into bytes or something.

Edit: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.

Steve
  • 31,144
  • 19
  • 99
  • 122
travis
  • 35,751
  • 21
  • 71
  • 94

7 Answers7

276

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)

Steve
  • 31,144
  • 19
  • 99
  • 122
  • The main issue I was having was not having a reference to System.Web in my solution, but I wasn't aware of EscapeUriString, thanks! – travis Jan 03 '11 at 16:29
  • 64
    In contrast to encodeURIComponent(), Uri.EscapeUriString() doesn't encode "+" to "%2b". Use Uri.EscapeDataString() instead. – jwaliszko Apr 30 '12 at 10:17
  • 6
    Use WebUtility instead of HttpUtility to avoid having to reference System.Web. HttpUtility doesn't exist in .NET Core. – Steven De Kock Dec 31 '15 at 01:15
  • 3
    @Steve Would you consider making your last paragraph bold? It seems to be the most important thing to know on this page, and it needs more visibility. – Timo Aug 25 '16 at 15:45
  • Also see this answer for more explanation on the difference between Uri.EscapeUriString and Uri.EscapeDataString: https://stackoverflow.com/questions/4396598/whats-the-difference-between-escapeuristring-and-escapedatastring – Jason Mar 16 '17 at 16:12
  • See this answer for more explanation on the difference between HttpUtility.UrlEncode and HttpUtility.UrlPathEncode https://stackoverflow.com/questions/4145823/httpserverutility-urlpathencode-vs-httpserverutility-urlencode – Jason Mar 16 '17 at 16:30
  • `UrlPathEncode` and `EscapeUriString` do not encode ampersand `&` but `Uri.EscapeDataString` and `HttpUtility.UrlEncode()` do – nothingisnecessary Mar 28 '17 at 18:52
  • Kudos to Steve for providing this excellent answer and Tim for the edited version. This work well and save my nerves after a very long search. To all of you who always contribute to this very useful platform, I say thank you! – omostan Apr 08 '22 at 08:59
  • `EscapeUriString` has been marked as absolete starting from .NET 6 because it can corrupt the Uri string in some cases. Use `EscapeDataString` instead. See: https://learn.microsoft.com/en-us/dotnet/fundamentals/syslib-diagnostics/syslib0013 – H. Pauwelyn Jun 19 '23 at 13:38
22

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

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

Gabe
  • 84,912
  • 12
  • 139
  • 238
David Thibault
  • 8,638
  • 3
  • 37
  • 51
  • I should've been more specific: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel. – travis Sep 17 '08 at 19:15
  • 5
    You can add a reference to the System.Web assembly – David Thibault Sep 17 '08 at 19:18
  • 2
    HtmlEncoding is an entirely different thing. UrlEncode is a non-sensical API which should never be used. It doesn't make sense to encode an entire URL (unless you actually want to encode its value to use as a parameter - but that's not what this does). The point of encoding/escaping is that you're conveying that a reserved character should be passed through without its usual meaning (e.g. that ? identifies the query, or & separates query parameters). This requires knowledge that UrlEncode does not and cannot have. – Brandon Paddock Apr 15 '16 at 19:53
19

I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this

c# CODE:

string a = "!@#$%^&*()_+ some text here али мамедов баку";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");

the result is: !%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83

After you decode It with Javascript's decodeURLComponent();

you will get this: !@#$%^&*()_+ some text here али мамедов баку

Thank You for attention

dana
  • 17,267
  • 6
  • 64
  • 88
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
13

System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.

Echilon
  • 10,064
  • 33
  • 131
  • 217
10

For a Windows Store App, you won't have HttpUtility. Instead, you have:

For an URI, before the '?':

  • System.Uri.EscapeUriString("example.com/Stack Overflow++?")
    • -> "example.com/Stack%20Overflow++?"

For an URI query name or value, after the '?':

  • System.Uri.EscapeDataString("Stack Overflow++")
    • -> "Stack%20Overflow%2B%2B"

For a x-www-form-urlencoded query name or value, in a POST content:

  • System.Net.WebUtility.UrlEncode("Stack Overflow++")
    • -> "Stack+Overflow%2B%2B"
Cœur
  • 37,241
  • 25
  • 195
  • 267
10

Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.

Billy Jo
  • 1,326
  • 19
  • 32
  • 1
    Uri.EscapeUriString() didn't do anything for me, but I was able to properly url-encode the strings using Uri.EscapeDataString() – Toland Hon Feb 13 '14 at 01:15
  • 4
    @TolandHon: Indeed. The reason is that `Uri.EscapeUriString()` corresponds to JavaScript's `encodeURI()` - which preserves URI-reserved chars. such as `/`, `&`, ... as-is (plus `#`), whereas - as you've discovered, it is `Uri.EscapeDataString()` that corresponds to JavaScript's `encodeURIComponent()`. – mklement0 Sep 18 '16 at 20:42
6

You can use the Server object in the System.Web namespace

Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.

Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.

Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173