174

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.

7 Answers 7

294

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)

Sign up to request clarification or add additional context in comments.

9 Comments

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!
In contrast to encodeURIComponent(), Uri.EscapeUriString() doesn't encode "+" to "%2b". Use Uri.EscapeDataString() instead.
Use WebUtility instead of HttpUtility to avoid having to reference System.Web. HttpUtility doesn't exist in .NET Core.
@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.
Also see this answer for more explanation on the difference between Uri.EscapeUriString and Uri.EscapeDataString: stackoverflow.com/questions/4396598/…
|
23

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

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

3 Comments

I should've been more specific: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.
You can add a reference to the System.Web assembly
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.
21

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

2 Comments

Works, but you can simply use Uri.EscapeDataString("!@#$%^&*()_+ some text here али мамедов баку") instead.
Actually, Uri.EscapeDataString encodes the characters '(' and ')' while HttpUtility.UrlEncode does not.
16

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

Comments

11

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"

Comments

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.

2 Comments

Uri.EscapeUriString() didn't do anything for me, but I was able to properly url-encode the strings using Uri.EscapeDataString()
@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().
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.

1 Comment

The Server object is inaccessible from a windows app

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.