c# - How to get all sections of a specific type -
let's have following in 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 want either section, can them name pretty easily:
interestingthingssection interesting = (interestingthingssection)configurationmanager.getsection("interestingthings"); interestingthingssection more = (interestingthingssection)configurationmanager.getsection("moreinterestingthings"); however, relies on code knowing how section named in config - , named anything. i'd prefer ability pull sections of type interestingthingssection config, regardless of name. how can go in flexible way (so, supports both app configs , web configs)?
edit: if have configuration already, getting actual sections isn't difficult:
public static ienumerable<t> sectionsoftype<t>(this configuration configuration) t : configurationsection { return configuration.sections.oftype<t>().union( configuration.sectiongroups.sectionsoftype<t>()); } public static ienumerable<t> sectionsoftype<t>(this configurationsectiongroupcollection collection) 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 configuration instance in generally-applicable way? or, how know if should use configurationmanager or webconfigurationmanager?
so far, appears best way:
var config = hostingenvironment.ishosted ? webconfigurationmanager.openwebconfiguration(null) // web app. : configurationmanager.openexeconfiguration(configurationuserlevel.none); // desktop app.
Comments
Post a Comment