Alex Rivera | Logout

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

Asked 2008-09-17T19:05:10.323
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.

Edit
Report

2 Answers

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

answered 2008-09-17T19:06:21.647
16

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

answered 2009-03-06T18:46:22.697

Your Answer