Search code examples
c#special-charactersconfigurationmanager

ConfigurationManager parser cannot read special character in c#


I have encountered an error "Configuration system failed to initialize" while loading from app.config file.

In my app.config file, i have a custom section where the password key has a special character value.

<appSettings>
  <add key="UserName" value="Alex" />
  <add key="Password" value="Test&123<456" />
</appSettings>

When the application step in the code as to read the app.config file. The application crash with the error message shown above.

...
_password = System.Configuration.ConfigurationManager.AppSettings["UserName"];
_password = System.Configuration.ConfigurationManager.AppSettings["Password"];
...

As long as there is a special character in the app.config file, the system could not read at all.

Is there is way to overcome this problem? Further i have found a site with an alternate solution. That is to change the special character to htmlcode, but then this do not sound right if we are to ask the end user to do this.

Is there anyway to overcome this problem?? Thanks


Solution

  • Use the static method

    HttpUtility.HtmlEncode
    

    to change & to &amp;

    Use

    HttpUtility.HtmlDecode
    

    to do the reverse.

    Whether or not a end user enters a special character, the HTML encoding and decoding should be invisible to the end user.