问题描述
我已经设置了我的App.Config中的一些自定义配置部分,这样,我现在有一个configSection看起来像这样。
I've set up some custom config sections in my App.Config, such that I now have a configSection that looks like this.
<configSections>
<section name="Section1" type="ConfigSections.MySection, MyNamespace"/>
<section name="Section2" type="ConfigSections.MySection, MyNamespace"/>
<section name="Section3" type="ConfigSections.MySection, MyNamespace"/>
</configSections>
我想要做的是阅读的本节的代码,以便找出在运行时我有什么部分。我曾尝试:
What I want to do is to read this section in code in order to find out at runtime what sections I have. I have tried:
var mySections = ConfigurationManager.GetSection("configSections");
但这种返回null。我敢肯定,我失去了一些东西简单,但我无法找到如何做这样的事情。
but this returns null. I'm sure I'm missing something simple, but I cannot find anything about how to do this.
感谢
推荐答案
使用的 -property得到声明配置节的名称。然后,可选,如果你需要,可以使用 ConfigurationManager.GetSection()
来检索各个部分。
Use the Configuration.Sections
-property to get the names of the declared configuration sections. Then, optionally if you need, use ConfigurationManager.GetSection()
to retrieve an individual section.
请注意,您可能要使用的或 ConfigSource
各自的找到出了节在配置文件实际上是宣告,或从的machine.config
继承或以其他方式。
Note that you may want to use the value of the SectionInformation.IsDeclared
or ConfigSource
of the respective ConfigurationSection.SectionInformation
to find out of the section was actually declared in your configuration file, or is inherited from machine.config
or otherwise.
例如:
var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var localSections = cfg.Sections.Cast<ConfigurationSection>()
.Where(s => s.SectionInformation.IsDeclared);
最后,请注意,这种方法只会让你配置部分。它不会返回配置部分,它本身是一个<内部; sectionGroup>
。对于他们来说,你首先需要遍历 Configuration.SectionGroups
,它有它自己的 -property包含每节组部分。它也可以包含嵌套节组,通过的每个 ConfigurationSectionGroup
实例的属性。
Finally, note that this approach will only get you configuration sections. It will not return configuration sections, which are itself inside a <sectionGroup>
. For them, you would first need iterate over Configuration.SectionGroups
, which has it's own Sections
-property that contains the per section group sections. It can also contain nested section groups, again accessible via the SectionGroups
property of each ConfigurationSectionGroup
instance.
这篇关于如何阅读configSections的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!