Sri Reddy
Sri Reddy

Reputation: 7012

C# update custom config section programmatically

I can easily update the app settings dynamically like

System.Configuration.Configuration configDefault = null;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                        fileMap.ExeConfigFilename = configFileName;
                        configDefault = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

configDefault.AppSettings.Settings[key].Value = "some value";

How can I replace the existing config section values in memory, I don't want to update the app.config itself? Current app.config looks like:

 <SomeCustomSection>
    <group name="mygroup" isenabled ="true">
      <subscriber name="customer" log="true" isenabled="false"/>
      <subscriber name="order" log="true" isenabled="false"/>
    </group>
  </SomeCustomSection>

I am overriding the config values from another config file.

SomeConfiguration sectionClient = (SomeConfiguration)configClient.GetSection("SomeCustomSection");
SomeConfiguration sectionDefault = (SomeConfiguration)configDefault.GetSection("SomeCustomSection");
foreach (var groupClient in sectionClient.Groups)
{
    var groupDefault = sectionDefault.Groups[groupClient.Name];
    groupDefault.IsEnabled = groupClient.IsEnabled;
    foreach(var sub in groupClient.Subscribers)
    {
        var subDefault = groupDefault.Subscribers[sub.Name];
        subDefault.Log = sub.Log;
        subDefault.IsEnabled = sub.IsEnabled;
    }
}

How should i update the Configuration object configDefault with the updated section? Something like:

configDefault.Sections["SomeCustomSection"] = sectionDefault;

Upvotes: 1

Views: 1490

Answers (1)

Craig
Craig

Reputation: 119

I don't know of a way to do it in memory. Even the AppSettings update code you include doesn't update config in memory in the sense that if the ConfigurationManager.AppSettings is checked after changing a setting in a loaded mapped config, it still reflects what's in the file <app>.exe.config. At least that's how it behaves when I try the code you have because the config you're changing is not the config loaded by ConfigurationManager.

If changing only the configuration loaded by ConfigurationManager.OpenMappedExeConfiguration is what you need then the code you show is already changing the config sections. There's nothing to set.

If you need the changed configuration to be available elsewhere without passing the modified configuration around, you'll have to save, refresh and then later restore the <app>.exe.config file to its previous state:

 configDefault.Save();
 ConfigurationManager.RefreshSection(SomeCustomSection);

Upvotes: 1

Related Questions