Search code examples
c#app-configconfigurationmanager

C# How can I get the number (count) of keys in <configSections>


I'm trying to get the number of configuration sections in my app.Config in order to initialize an int var to this # and read the items in a loop dinamically at run time.

<configSections>
  <section name="Section1" type="ConfigSections.MySection, MyNamespace"/>
  <section name="Section2" type="ConfigSections.MySection, MyNamespace"/>
  <section name="Section3" type="ConfigSections.MySection, MyNamespace"/>
</configSections>

In this example, the count would be 3.

I have tried with ConfigurationSectionGroup and other classes but either their .Count property does not return the correct number (they seem to inherit additional sections/groups from elsewhere) or the class simply doesn't have a Count property.

I may go through the section and count each item to get a # but I wonder if there's a direct method or property to get this # at once.

Thanks.


Solution

  • Use XmlDocument class.

    But first add System.Xml.XmlDocument in your project, using NuGet Packages.

    XML file

    <?xml version="1.0" encoding="UTF-8" ?>
    <configSections>
      <section name="Section1" type="ConfigSections.MySection, MyNamespace"/>
      <section name="Section2" type="ConfigSections.MySection, MyNamespace"/>
      <section name="Section3" type="ConfigSections.MySection, MyNamespace"/>
      <other name="Other" type="ConfigSections.Other, MyNamespace"/>
    </configSections>
    

    Code example

    XmlDocument xml = new XmlDocument();
    xml.Load(".../test.xml"); //path to xml file
    
    XmlNodeList xnList = xml.SelectNodes("/configSections/section");
    Console.WriteLine(xnList.Count);
    foreach (XmlNode xn in xnList)
    {
        string value = xn.Attributes.GetNamedItem("name").Value;
        Console.WriteLine(value);
    }
    

    Result

    3
    Section1
    Section2
    Section3