How to get all sections by name in the sectionGroup applicationSettings in .Net 2.0

后端 未结 1 1582
悲&欢浪女
悲&欢浪女 2020-12-09 18:17

Here\'s the idea I had:

I want a small executable to have an app.config file with multiple sections that are situated under the sectionGroup \"applicationSettings\"

相关标签:
1条回答
  • 2020-12-09 19:12

    Take a look at the ConfigurationManager.OpenExeConfiguration function to load in your configuration file.

    Then on the System.Configuration.Configuration class that you'll get back from ConfigurationManager.OpenExeConfiguration you'll want to look at the SectionGroups property. That'll return a ConfigurationSectionGroupCollection in which you'll find the applicationSettings section.

    In the ConfigurationSectionGroupCollection there will be a Sections property which contains the Executable and FirstModule ConfigurationSection objects.

    var config = ConfigurationManager.OpenExeConfiguration(pathToExecutable);
    var applicationSettingSectionGroup = config.SectionGroups["applicationSettings"];
    var executableSection = applicationSettingSectionGroup.Sections["Executable"];
    var firstModuleSection = applicationSettingSectionGroup.Sections["FirstModule"];
    

    You will want to check for null after getting the ConfigurationSectionGroupCollection object or ConfigurationSection objects. If they are null they don't exist in the configuraiton file.

    You can also get the sections by using ConfigurationManager.GetSection

    var executableSection = (ClientSettingsSection)ConfigurationManager
        .GetSection("applicationSettings/Executable");
    var firstModuleSection = (ClientSettingsSection)ConfigurationManager
        .GetSection("applicationSettings/FirstModule");
    

    Again, if the objects are null they don't exist in the configuration file.

    To get a list of all the section names and groups you could do:

    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
    // use the line below instead if you want to load an app.config for a
    //   different application other than the one the code is running in
    // var config = ConfigurationManager.OpenExeConfiguration(pathToExecutable);
    
    var names = new List<string>();
    foreach (ConfigurationSectionGroup csg in config.SectionGroups)
        names.AddRange(GetNames(csg));
    
    foreach (ConfigurationSection cs in config.Sections)
        names.Add(cs.SectionInformation.SectionName);
    
    private static List<string> GetNames(ConfigurationSectionGroup configSectionGroup)
    {
        var names = new List<string>();
    
        foreach (ConfigurationSectionGroup csg in configSectionGroup.SectionGroups)
            names.AddRange(GetNames(csg));
    
        foreach(ConfigurationSection cs in configSectionGroup.Sections)
            names.Add(configSectionGroup.SectionGroupName + "/" + cs.SectionInformation.SectionName);
    
        return names;
    }
    
    0 讨论(0)
提交回复
热议问题