How to override settings.settings variable by app.config variable

Posted on

Problem :

How can I change (or override) a settings.settings variable by adding a variable to the app.config on production?

Is this possible anyway?

Solution :

You have to directly reference the applicationSettings you’re trying to override and explicitly specify the property that has a replaced value.

  <!-- section definitions for all elements in <configuration> tag -->
    <!-- section group, meaning: there will be a <applicationSettings> tag in you configuration-->
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <!-- defines that there will be a <appname.Properties.Settings> tag inside your <applicationSettings> tag -->
      <section name="appname.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

      <!-- name of the property you want to override -->
      <setting name="setting1" serializeAs="String">
        <!-- new value -->
        <value>new string value</value>

It depends on the scope of the settings. If its an application scope setting changing its value in app.config is sufficient.

However, if its a user scope setting then the value present in app.config is just the default used to new users and every user that already used the application will have the currently used value stored in a separate file, the user.config, so changing the value in app.config will have no effect to users that already run the application once.

Due to this changing the value of an user scope setting can be a troublesome task. You can check the following answer for more information on changing a user scope setting:

Changing User Scope Application Setting

Use different config files for production and for you. Basically on production you would compile in RELEASE, so if you use Visual Studio for it, use post build events to copy RELEASE config file in case you prepare a build for production.

I would prefer this instead of changing it from the code, as for someone else is much easier to see the differenc in config file, then going deep into the code to find all the if/else stuff.

For an application scope connection string value:

    <add name="appname.Properties.Settings.setting1" connectionString="test string" providerName="dbProvider"/>

Only through code:


 if (bool.Parse(ConfigurationManager.AppSettings["overridethis"].ToString()))
     //use overridden value

If however, your issue is maintaining different configuration values in different environments, then I would use AppSettings instead.

You can then use a developer override file.

 <appSettings file="..user.config">


Leave a Reply

Your email address will not be published. Required fields are marked *