tags:

views:

1644

answers:

3

How do i escape text for html use in C#? I want to do

sample="<span>blah<span>"

and have

<span>blah<span>

show up as plain text instead of blah only with the tags part of the html :(. Using C# not ASP

A: 

You can use actual html tags <xmp> and </xmp> to output the string as is to show all of the tags in between the xmp tags.

Or you can also use on the server Server.UrlEncode or HttpUtility.HtmlEncode.

Andrew Siemer
I made the question more clear. I dont want the tags to be part of html as the user can do </pre> and break it.
acidzombie24
+1 for promoting the infamous `xmp` tag
Ron Klein
+6  A: 
using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);
Michael S. Scherotter
Perfect, works as i expected.
acidzombie24
If you also want to encode unicode characters to non-unicode, check out this: http://stackoverflow.com/questions/82008/non-unicode-xml-representation
Gyuri
+1  A: 

Also, you can use this if you don't want to use the System.Web assembly:

var encoded = System.Security.SecurityElement.Escape(unencoded)
ondatra