views:

3281

answers:

5

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.

+10  A: 

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

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

David Thibault
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
You can add a reference to the System.Web assembly
David Thibault
I just realized that, thanks!
travis
+4  A: 

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
The Server object is inaccessible from a windows app
travis
+9  A: 

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.

Bill Ayakatubby
+2  A: 

System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.Escape**Data**String() worked for me.

Echilon
+1  A: 

Thanks guys!!! I used HttpUtility.HtmlEncode(). Needed to escape Spanish accents (á, é, í... and ñ, Ñ) and it worked perfect!!!!