Escape text for HTML

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


using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

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

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

Per this article, the difference between System.Security.SecurityElement.Escape() and System.Web.HttpUtility.HtmlEncode() is that the former also encodes apostrophe (') characters.


If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System

var encoded = WebUtility.HtmlEncode(unencoded);

This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.


In ASP.NET 4.0 there's new syntax to do this. Instead of

<%= HttpUtility.HtmlEncode(unencoded) %>

you can simply do

<%: unencoded %>

Read more here:

New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)