访问 AppConfig 中的多个部分

Accessing multiple sections in AppConfig

我有一个 AppConfig 文件,如下所示。我正在尝试遍历配置部分并根据部分名称获取部分名称,它应该 select 适当的 appSettings。例如,当第一部分是 VehicleConfig 时,它应该自动 select VehicleConfig 的 appSettings。我需要这个自动 selection,因为我有多个部分,我必须根据不同部分的名称获取不同部分的 appSettings。

    <configuration>
     <configSections>
       <sectionGroup name="group1">
         <section name="Vehiclefeature"type="System.Configuration.NameValueSectionHandler" />
         <section name="LiveDownloader" type="System.Configuration.NameValueSectionHandler" />
       </sectionGroup>
     </configSections>
     <VehicleFeature>
         <add key="FileRoot" value="C:\FilesToUpload" />
         <add key="Project" value="BigDataTest" />
         <add key="Dataset" value="StoreServer" />
     </VehicleFeature>
     <LiveDownloader>
        <add key="FileRoot" value="C:\FilesToUpload" />
        <add key="Project" value="BigDataTest" />
        <add key="Dataset" value="BQSMeasure" />
     </LiveDownloader>
    </configuration>

我试过这段代码,当遇到第二个 for-each 循环时,它抛出错误 "Unrecognized element appSettings inside VehicleConfig"。我尝试删除 appSettings,但随后它抛出 "Unrecognized element add"。我想知道我是否可以在 VehicleConfig 中包含这些元素。

 System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

 ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups;

         foreach (ConfigurationSectionGroup group in sectionGroups)
        // Loop over all groups
        {
            Console.WriteLine(group);
            if (group.Name == "FileCheckerConfigGroup")
            {
                foreach (ConfigurationSection configurationSection in group.Sections)
                {
                    var section = ConfigurationManager.GetSection(configurationSection.SectionInformation.SectionName) as NameValueCollection;
                }
            }
        }

感谢任何帮助!!

        System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        // Get the collection of the section groups.
        ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups;

        // Show the configuration values
        foreach (ConfigurationSectionGroup group in sectionGroups)
        // Loop over all groups
        {
            if (group.Name == "group1")
            {
                foreach (ConfigurationSection configurationSection in group.Sections)
                {
                  var section1 = ConfigurationManager.GetSection(configurationSection.SectionInformation.SectionName) as NameValueCollection;

                }
            }
         }