Override config settings

Viewed 11516

I have a config file that is used in several projects, general.config, looks like:

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
   <add key="mykey1" value="myvalue1"/>    
   <add key="mykey2" value="myvalue2"/>
</appSettings>

In one of the projects, I need to override one of the two settings. So the app.config of this project looks like:

<?xml version="1.0"?>
<configuration>
  <appSettings file="general.config">
    <remove key="mykey1"/>
    <add key="mykey1" value="anothervalue"/>
    <add key="mykey3" value="myvalue3"/>
  </appSettings>  
</configuration>

But remove is not working here. How can I override mykey1 without breaking mykey2? add works in this case. I can get myvalue3 from ConfigurationManager.

EDIT: general.config is copied to output folder automatically when compiling. Don't worry about the path issue. Currently I got:

ConfigurationManager.AppSettings["mykey1"] 
     //I got "myvalue1", but I want "anothervalue" here
     //that is, this item is "overrided", just like virtual methods in C#
ConfigurationManager.AppSettings["mykey2"] 
     //this setting will not be modified, currently it works fine
ConfigurationManager.AppSettings["mykey3"]   //good 
4 Answers

Your use of the file attribute to load common settings with an expectation that keys added directly to the <appSettings> element would override those common settings is understandable, but unfortunately that is not how it works.

Microsoft's intention was for the file attribute to load common settings that override the individual application's settings.

This is discussed in some detail in the Microsoft Documentation

To overcome this problem, we very occasionally declare base settings in the common file, and then appropriately named overrides in the application configuration. However this does require additional code which is a bit ugly. e.g.

var config = ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER_OVERRIDE"]
    ?? ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER"]
    ?? "ActiveMQ";

<appSettings file="common.config"> 
    <!-- Override the common values -->
    <add key="MSG_QUEUE_PROVIDER_OVERRIDE" value="RabbitMQ"/>
</appSettings>
Related