tags:

views:

155

answers:

3

Basically a dup of this question using php, but I need it for C#.

I need to be able to replace any & that is not currently not any HTML entity (e.g. &) before outputting to screen. I was thinking a regex, but I'm not sure if .Net has something built in that will do this.

+1  A: 

You could always HTML Decode the string (which would turn any HTML symbols into their display equivalents), replace any &'s, and then Encode the string again (which turns the symbols back into what they were originally). You might need to watch for side effects though.

Tejs
Jonas
Tejs
corymathews
Seems like a decode/encode cycle would take care of it without having to replace amperstands. Decode would transform already encoded characters back to plain text, and encoding would reverse it while also handling characters that weren't properly encoded before.
Anthony Pegram
@cory, your idea would make " => "
Anthony Pegram
+2  A: 

You can use HttpUtility.HtmlEncode.
Whithing the context of a page or UserControl, you can use Server.HtmlEncode.

Kobi
+2  A: 

Better AntiXss.HtmlEncode, prevents XSS.

KMan