views:

38

answers:

1

I need to store an escaped html string in a key in web.config using the KeyValueConfigurationElement.Save method built into framework 3.5. But when I try to do so, it keeps escaping my ampersands.

Code looks like this:

strHTML = DecodeFTBInput(FTB1.Text)

FTB1.Text is a string of HTML, like this: <b><font color="#000000">Testing</font></b>

DecodeFTPInput uses the String.Replace() method to change < and > to &lt; and &gt;, and " to &quot;.

Given the above string and function, let's say strHTML now contains the following:

&lt;b&gt;&lt;font color=&quot;#000000&quot;&gt;Testing&lt;/font&gt;&lt;/b&gt;

Of course I can manually edit web.config to store the correct value, but I need the authenticated admin user to be able to change the html themselves.

The problem is that when I try to save this string into its key in web.config, it escapes all ampersands as &amp; which ruins the string.

How can I get around this?

+1  A: 

web.config is an XML file, so when it writes values there the .NET Framework stores strings using HTML encoding, replacing the < > & characters with &lt;, &gt; and &amp;, and much more besides.

You'll need to stop your DecodeFTPInput method from HTML encoding the string if you want the HTML in the web.config file to be editable. Otherwise you'll be HTML encoding twice, which isn't the result you want!

Jeremy McGee
I see your point, thanks for the answer. I'll just Base64 encode the thing, since I think that only uses XML-safe characters. If that's no joy, I'll MD5 hash the bastard, lol. I can reconvert before I assign the value to an asp:literal.
Stephen Falken
derp, md5 is one-way, but the point remains, i'll crunch it into integers if I have to.
Stephen Falken