5

I have a string with special characters like this:

äöüß&

Now I want to put that in an HTML document and need to escape these characters. Is there an elegant way doing this?

I could do this:

string html;
html = html.Replace("ü", "uu¨");
html = html.Replace("ß", "ß");
....

But I don't want to do that for all possible special characters.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
juergen d
  • 201,996
  • 37
  • 293
  • 362

3 Answers3

13

Let the Framework do the work for you.

You could try HtmlEncode:

string encodedHtml = Server.HtmlEncode(html);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • @juergend - Check the documentation I linked to. Has the namespace and the assembly (in case you need to add a reference). – Justin Niessner Jan 02 '12 at 19:26
  • 7
    I didn't see that at first. Actually even after using the `System.Web` namespace and referencing the System.Web.dll in my Project, VS2010 still can't find the Server class. But it finds this which works perfectly: `HttpUtility.HtmlEncode` – juergen d Jan 02 '12 at 19:43
10

There is also this, intended for XML, but it should work just fine with HTML:

System.Security.SecurityElement.Escape( string s );

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
2

I recommend getting into the habit of using Microsoft's AntiXSS Library, and calling

AntiXSS.HtmlEncode(yourstring);

if you need to include it in the body, or

AntiXSS.HtmlAttributeEncode(yourstring);

if it is going inside an HTML attribute.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rejj
  • 1,216
  • 7
  • 13