user3447653
user3447653

Reputation: 4158

Loop through different sections of appConfig file

I have an AppConfig file as shown below. I am trying to loop through the configsections and get the section name, based on the section name, it should select the appropriate appSettings. For example, when the first section is VehicleConfig, it should automatically select the appSettings of VehicleConfig. I need this automatic selection because i have multiple sections and I have to get the appSettings of different sections based on their section names.

    <configuration>
     <configSections>
      <sectionGroup name = "mySection">
       <section name="VehicleConfig"/>
       <section name="LiveDownloaderConfig"/>
      </sectionGroup>
     </configSections>
     <VehicleConfig>
       <appSettings>
         <add key="FileRoot" value="C:\FilesToUpload" />
         <add key="Project" value="BigDataTest" />
         <add key="Dataset" value="StoreServer" />
       </appSettings>
     </VehicleConfig>
     <LiveDownloaderConfig>
       <appSettings>
        <add key="FileRoot" value="C:\FilesToUpload" />
        <add key="Project" value="BigDataTest" />
        <add key="Dataset" value="BQSMeasure" />
       </appSettings>
     </LiveDownloaderConfig>
  </configuration>

I have tried this code and when the second for-each loop is hit, it throws the error "Unrecognized element appSettings inside VehicleConfig". I tried removing the appSettings, but then it throws "Unrecognized element add". I wonder whether i can have these elements inside 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;
                }
            }
        }

Any help is appreciated !!

Upvotes: 2

Views: 10912

Answers (3)

Scott Hannen
Scott Hannen

Reputation: 29222

Usually we get to the Configuration through the ConfigurationManager. But in this case you need to go straight to the Configuration object. It's a little bit of a nuisance because how you access it varies between web applications and other applications.

Here are a few samples:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/")

Once you have a reference to that object you can use its .SectionGroups and .Sections properties to iterate through the various sections.


After reading the comments, I think this is more specifically what you're looking for. I forgot how completely non-intuitive configuration sections were.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="mySettings" type="System.Configuration.AppSettingsSection"/>
    <section name="myOtherSettings" type="System.Configuration.AppSettingsSection"/>
  </configSections>
  <mySettings>
    <add key="foo" value="bar"/>
  </mySettings>
  <myOtherSettings>
    <add key="yourUncle" value="bob" />
  </myOtherSettings>
</configuration>

Then to read them,

class Program
{
    static void Main(string[] args)
    {
        var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        foreach (var sectionKey in configuration.Sections.Keys)
        {
            var section = configuration.GetSection(sectionKey.ToString());
            var appSettings = section as AppSettingsSection;
            if (appSettings == null) continue;
            Console.WriteLine(sectionKey);
            foreach (var key in appSettings.Settings.AllKeys)
            {
                Console.WriteLine("  {0}: {1}", key, appSettings.Settings[key].Value);
            }
        }
        Console.ReadLine();
    }
}

The output:

appSettings  
myOtherSettings    
  yourUncle: bob  
mySettings   
  foo: bar  

You'd need to add a little extra to also iterate through nested configuration sections, but I can't leave you without any fun.

Upvotes: 3

suulisin
suulisin

Reputation: 1434

please try with this

foreach (var key in System.Configuration.ConfigurationSettings.AppSettings)
{

}

Upvotes: 2

War
War

Reputation: 8618

The easy way is to just treat the file like a normal XML file and perhaps use XDocument then you can just query it with linq ...

var config = XDocument.Load(File.OpenRead("app.config"));
var sections = config.Descendants("configuration");

foreach(var section in sections) {
    // stuff
}

To get a particular sections settings you want to use a deeper xpath expression ...

var sectionName = "VehicleConfig";
var settings = config.Descendants("configuration/" + sectionName + "/appSettings");

you can then loop through those settings with a simple foreach as above

Upvotes: 2

Related Questions