Config Files & Ampersands

Sometimes you have the requirement to use an Ampersand within your web.config or app.config file. It may be something like storing a URL in an Application Setting, like the following example:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<configuration>

  <appSettings>

    <add key=”CatManUrl” value=”http://www.testsite.com/default.aspx?v=2&p=3″ />

  </appSettings>

</configuration>

However, you will quickly realize that this generates an error in your application, since you cannot use Ampersands in your config files. Luckily, you can simply use html encoded version of the ampersand and the xml parser will transform it for you automatically. Here is what your app setting looks like now:

<add key=”CatManUrl” value=”http://www.testsite.com/default.aspx?v=2&amp;p=3″ />

And you simply continue to pull the value as your normally might:

string testString = ConfigurationManager.AppSetting[“CatManUrl”];

Now testString will contain the appropriate value: http://www.testsite.com/default.aspx?v=2&p=3

Keep this in mind working with other encoded characters too!!