232

I've got a C# program with values in a config file. What I want is to store ampersands for an url value like...

<appSettings>
  <add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
</appSettings>

But I get errors building my site. The ampersand is not allowed. I've tried various forms of escaping the ampersands to no avail. Anyone know of the correct form to do this? All suggestions are welcome.

Rob Segal
  • 7,315
  • 12
  • 42
  • 69

4 Answers4

467

Use "&amp;" instead of "&".

Eric Rosenberger
  • 8,847
  • 1
  • 22
  • 24
  • 2
    I seriously thought I had tried this. I think I missed the trailing ";" at the end. Anyways it does works so thanks for the feedback Eric. – Rob Segal Dec 17 '08 at 22:23
  • 7
    This works, but I have to put a string.Replace("&","&") whereever I access this setting, or else the browser won't properly detect it when you click on the link :/ – DLeh May 16 '14 at 15:37
  • Well... that's pretty disappointing. I mean, that the ConfigurationManager does not automatically unescape these &xyl; characters when getting them from the config file. – Efrain Oct 27 '17 at 12:16
  • @Efrain not sure what DLeh is talking about exactly, but unescape definitely works fine. Just tested this with standard `appSettings` as well as a custom `NameValueCollection` section: ampersand is unescaped properly on both. – julealgon Nov 04 '19 at 22:25
28

Have you tried this?

<appSettings>  
  <add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/>
<appSettings>
BenAlabaster
  • 37,733
  • 21
  • 106
  • 149
4

I think you should be able to use the HTML escape character (&). They can be found at http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php

ICR
  • 13,548
  • 4
  • 46
  • 77
2

Although the accepted answer here is technically correct, there seems to be some confusion amongst users based on the comments. When working with a ViewBag in a .cshtml file, you must use @Html.Raw otherwise your data, after being unescaped by the ConfigurationManager, will become re-escaped once again. Use Html.Raw() to prevent this from occurring.

user700390
  • 2,080
  • 1
  • 18
  • 24