my779
my779

Reputation: 79

Get Section Names Programmatically from App.config C#

Is there a way to programmatically get the section names by doing a loop instead of hard coding the names yourself?

For instance:

<configuration>
  <configSections>
    <section name="Test1"  type="System.Configuration.NameValueSectionHandler"/>
    <section name="Test2" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>

Hardcoding:

var section = ConfigurationManager.GetSection("Test1") as NameValueCollection;
var section = ConfigurationManager.GetSection("Test2") as NameValueCollection;

I do not want to hard code the Test1 and Test2 section names in the code.

Upvotes: 1

Views: 1603

Answers (1)

Volkan Paksoy
Volkan Paksoy

Reputation: 6957

You can get the section group names like this:

    static void Main(string[] args)
    {
        string configPath = @"..\..\App.config";
        var map = new ExeConfigurationFileMap();
        map.ExeConfigFilename = configPath;
        var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
        for (int i = 0; i < config.SectionGroups.Count; i++)
        {
            Console.WriteLine(config.SectionGroups[i].SectionGroupName);
        }
    }

Upvotes: 1

Related Questions