我在我的App.Config中设置了一些自定义配置部分,这样我现在有一个看起来像这样的configSection.
<configSections>
<section name="Section1" type="ConfigSections.MySection, MyNamespace"/>
<section name="Section2" type="ConfigSections.MySection, MyNamespace"/>
<section name="Section3" type="ConfigSections.MySection, MyNamespace"/>
</configSections>
Run Code Online (Sandbox Code Playgroud)
我想要做的是在代码中阅读本节,以便在运行时找出我有哪些部分.我试过了:
var mySections = ConfigurationManager.GetSection("configSections");
Run Code Online (Sandbox Code Playgroud)
但是这会返回null.我确定我错过了一些简单的东西,但我找不到任何关于如何做到这一点的事情.
谢谢
使用Configuration.Sections-property获取声明的配置节的名称.然后,可选地,如果需要,用于ConfigurationManager.GetSection()检索单个部分.
请注意,您可能希望使用相应SectionInformation.IsDeclared或ConfigSource各自的值ConfigurationSection.SectionInformation来查找在配置文件中实际声明的部分,或继承自machine.config或以其他方式继承.
例:
var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var localSections = cfg.Sections.Cast<ConfigurationSection>()
.Where(s => s.SectionInformation.IsDeclared);
Run Code Online (Sandbox Code Playgroud)
最后,请注意,此方法只会为您提供配置部分.它不会返回配置节,它们本身在一个内部<sectionGroup>.对于他们来说,你首先需要迭代Configuration.SectionGroups,它有自己的Sections属性,包含每个部分组部分.它还可以包含嵌套的节组,也可以通过SectionGroups每个ConfigurationSectionGroup实例的属性访问.