App.config add nested group to existing node App.config add nested group to existing node xml xml

App.config add nested group to existing node


It took me a while to figure-out what was going on and tl;dr it seems, to me, there is a problem with the framework code itself, particularly method WriteUnwrittenConfigDeclarationsRecursive(SectionUpdates declarationUpdates, XmlUtilWriter utilWriter, int linePosition, int indent, bool skipFirstIndent) inside class MgmtConfigurationRecord. I don't want to write a long story but if you wish you could debug .Net framework code and see for yourself.

You can fix your code in following ways:

1. Save all groups together

private void SaveGroups(){    var config = GetConfig();    var root = new ConfigurationSectionGroup();    config.SectionGroups.Add(ROOT_GROUP, root);    config.Save(ConfigurationSaveMode.Modified);    ConfigurationManager.RefreshSection(root.Name);    var nested = new UserSettingsGroup();    root.SectionGroups.Add(GROUP_1, nested);    nested = new UserSettingsGroup();     root.SectionGroups.Add(GROUP_2, nested);    config.Save(ConfigurationSaveMode.Modified);    ConfigurationManager.RefreshSection(root.Name);}

2. Remove existing group items before adding a new one

private void SaveGroup2(){    var config = GetConfig();    var root = config.SectionGroups[ROOT_GROUP];    var existingGroups = new Dictionary<string, ConfigurationSectionGroup>();    while (root.SectionGroups.Count > 0)    {        existingGroups.Add(root.SectionGroups.Keys[0], root.SectionGroups[0]);        root.SectionGroups.RemoveAt(0);    }    config.Save(ConfigurationSaveMode.Modified);    existingGroups.Add(GROUP_2, new UserSettingsGroup());    foreach (var key in existingGroups.Keys)    {        existingGroups[key].ForceDeclaration(true);        root.SectionGroups.Add(key, existingGroups[key]);    }    config.Save(ConfigurationSaveMode.Modified);    ConfigurationManager.RefreshSection(root.Name);}


In your first update, you added GROUP_2 under the first entry under root:

    //nested1 is now the first entry under root due to Get(0)    var nested1 = root.SectionGroups.Get(0);     var nested2 = new UserSettingsGroup();    var nested3 = new UserSettingsGroup();    //I think you meant root here instead of nested1.    nested1.SectionGroups.Add("GROUP_2", nested2);