0

I'd like to know a way to get all the sections names inside the tag configSections on my App.Config file.

So far what I've found is something like this:

var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var localSections = cfg.Sections.Cast<ConfigurationSection>().Where(s => s.SectionInformation.IsDeclared);

But for some reason localSections always appears to be null. Here is how my app.config file looks like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
  <add key="frequency" value=""/>
</appSettings>
<configSections>
  <section name="Name1" type="System.Configuration.NameValueSectionHandler" />
  <section name="Name2" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<Name1>
  <add key="active" value="on"/>
  <add key="repeat" value="off"/>
</Name1>
<Name2>
  <add key="active" value="on"/>
  <add key="repeat" value="off"/>
</Name2>
</configuration>
Griswald90
  • 11
  • 2
  • this is not that difficult here is a link that I found quickly for you with a single google search http://stackoverflow.com/questions/17663305/reading-keyvalue-pairs-into-dictionary-from-app-config-configsection if that doesn't help then try doing a google search on your own.. it's not that Trivial – MethodMan Jan 23 '15 at 17:26
  • @MethodMan thank you for the comment! But that's not quite what I'm looking for... I can retrieve a section easily knowing the name of the section. But in this case I need to get first the property "name" from each section inside "configSections", that means only "Name1" and "Name2". – Griswald90 Jan 23 '15 at 17:41

1 Answers1

3

You can get SectionName by Section Information

string s;
var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var localSections = cfg .Sections.Cast<ConfigurationSection>().Where(s => s.SectionInformation.IsDeclared);
foreach( var i in localSections)
     s = i.SectionInformation.SectionName;
prasy
  • 250
  • 1
  • 14