Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape C# string to HTML [duplicate]

Tags:

html

c#

escaping

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.

like image 530
juergen d Avatar asked Jan 02 '12 19:01

juergen d


2 Answers

Let the Framework do the work for you.

You could try HtmlEncode:

string encodedHtml = Server.HtmlEncode(html);
like image 198
Justin Niessner Avatar answered Oct 25 '22 01:10

Justin Niessner


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

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

like image 45
Mike Nakis Avatar answered Oct 25 '22 01:10

Mike Nakis