Search code examples
c#configurationmanagerconfigurationelementconfigsection

Store same key in Machine.config and App.config


I'm holding a custom configuration section in machine.config of following structure:

<CustomSettings>
   <add key="testkey" local="localkey1" dev="devkey" prod="prodkey"/>
</CustomSettings>

Now, i want to be able to override the same key settings by storing the overrides in app.config like this:

<CustomSettings>
   <add key="testkey" dev="devkey1" prod="prodkey1"/>
</CustomSettings>

So that when i read it in code i'll get - dev="devkey1", prod="prodkey1", local="localkey1"

Problem is that when i read my custom config section like this:

CustomConfigurationSection section = ConfigurationManager.GetSection("CustomSettings") as CustomConfigurationSection;

i get an error stating that the key has already been added:

"The entry 'testkey' has already been added."

I modified making the ConfigElementCollection.Add function to check if the same key already exists but it didn't work.

Any ideas?


Solution

  • I ended up overriding BaseAdd in the ConfigurationElementCollection:

    protected override void BaseAdd(ConfigurationElement element)
        {
    
    
     CustomConfigurationElement newElement = element as CustomConfigurationElement;
    
          if (base.BaseGetAllKeys().Where(a => (string)a == newElement.Key).Count() > 0)
          {
            CustomConfigurationElement currElement = this.BaseGet(newElement.Key) as CustomConfigurationElement;
    
            if (!string.IsNullOrEmpty(newElement.Local))
              currElement.Local = newElement.Local;
    
            if (!string.IsNullOrEmpty(newElement.Dev))
              currElement.Dev = newElement.Dev;
    
            if (!string.IsNullOrEmpty(newElement.Prod))
              currElement.Prod = newElement.Prod;
          }
          else
          {
            base.BaseAdd(element);
          }
        }
    

    I hope it helps...