假设我在配置文件中有以下内容:
<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>
如果我想获取其中任意一个部分,可以很容易地通过名称获取它们:
InterestingThingsSection interesting = (InterestingThingsSection)ConfigurationManager.GetSection("interestingThings");
InterestingThingsSection more = (InterestingThingsSection)ConfigurationManager.GetSection("moreInterestingThings");
然而,这取决于我的代码知道配置中部分的名称 - 它可以被命名为任何内容。我更喜欢的是从配置中提取所有类型为
InterestingThingsSection
的部分,而不考虑名称。我该如何以灵活的方式实现这一点(因此,支持应用程序配置和Web配置)?编辑:如果您已经有了
Configuration
,获取实际的部分并不太困难: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;
}
然而,我该如何以一种普遍适用的方式获取Configuration
实例呢?或者说,我该如何知道是应该使用ConfigurationManager
还是WebConfigurationManager
呢?
Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
,如此处所述:如何确定应用程序是否为Web应用程序。 - Svein Fidjestøl