Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all sections of a specific type

Let's say I have the following in my config:

<configSections>
  <section name="interestingThings" type="Test.InterestingThingsSection, Test" />
  <section name="moreInterestingThings" type="Test.InterestingThingsSection, Test" />
</configSections>

<interestingThings>
  <add name="Thing1" value="Seuss" />
</interestingThings>

<moreInterestingThings>
  <add name="Thing2" value="Seuss" />
</moreInterestingThings>

If I want to get either section, I can get them by name pretty easily:

InterestingThingsSection interesting = (InterestingThingsSection)ConfigurationManager.GetSection("interestingThings");
InterestingThingsSection more = (InterestingThingsSection)ConfigurationManager.GetSection("moreInterestingThings");

However, this relies on my code knowing how the section is named in the config - and it could be named anything. What I'd prefer is the ability to pull all sections of type InterestingThingsSection from the config, regardless of name. How can I go about this in a flexible way (so, supports both app configs and web configs)?

EDIT: If you have the Configuration already, getting the actual sections isn't too difficult:

public static IEnumerable<T> SectionsOfType<T>(this Configuration configuration)
    where T : ConfigurationSection
{
    return configuration.Sections.OfType<T>().Union(
        configuration.SectionGroups.SectionsOfType<T>());
}

public static IEnumerable<T> SectionsOfType<T>(this ConfigurationSectionGroupCollection collection)
    where T : ConfigurationSection
{
    var sections = new List<T>();
    foreach (ConfigurationSectionGroup group in collection)
    {
        sections.AddRange(group.Sections.OfType<T>());
        sections.AddRange(group.SectionGroups.SectionsOfType<T>());
    }
    return sections;
}

However, how do I get the Configuration instance in a generally-applicable way? Or, how do I know if I should use ConfigurationManager or WebConfigurationManager?

like image 804
zimdanen Avatar asked Oct 20 '22 10:10

zimdanen


2 Answers

So far, this appears to be the best way:

var config = HostingEnvironment.IsHosted
    ? WebConfigurationManager.OpenWebConfiguration(null) // Web app.
    : ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Desktop app.
like image 178
zimdanen Avatar answered Nov 01 '22 09:11

zimdanen


Try to use ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) method. It opens the configuration file for the current application as a Configuration object.

MSDN documentation: https://msdn.microsoft.com/en-us/library/ms134265%28v=vs.110%29.aspx

like image 36
Ivan Doroshenko Avatar answered Nov 01 '22 10:11

Ivan Doroshenko