2012-04-26 100 views
4

我已经在我的App.Config中设置了一些自定义配置部分,这样我现在有了一个像这样的configSection。如何阅读configSections

<configSections> 
    <section name="Section1" type="ConfigSections.MySection, MyNamespace"/>  
    <section name="Section2" type="ConfigSections.MySection, MyNamespace"/>  
    <section name="Section3" type="ConfigSections.MySection, MyNamespace"/>  
</configSections> 

我想要做的就是阅读代码本节为了在运行时发现我有什么部分。我曾尝试过:

var mySections = ConfigurationManager.GetSection("configSections"); 

但是这会返回null。我确信我错过了一些简单的事情,但是我找不到如何做到这一点的任何事情。

感谢

+0

它认为你必须这样做:var mySections = ConfigurationManager.GetSection(“Section1”); – HW90 2012-04-26 10:47:35

+0

为了澄清,我非常高兴如何阅读“Section1”部分。我正在尝试阅读“configSections”部分,因此我不必在代码中对文本“Section1”进行硬编码。原因是我在运行时不知道我将会拥有多少节。 – bornfromanegg 2012-04-26 11:13:37

+0

换句话说,我希望能够读取我的App.Config中“configSections”元素(上面)中包含的每个“section”元素的“name”属性。 (这很难解释!) – bornfromanegg 2012-04-26 11:15:29

回答

5

使用Configuration.Sections -property得到声明构成部分的名称。然后,如有需要,可使用ConfigurationManager.GetSection()检索单个部分。

请注意,您可能需要使用SectionInformation.IsDeclared或相应ConfigurationSection.SectionInformationConfigSource的价值,找到段的出你的配置文件实际上是宣告,或从machine.config或以其他方式继承。

例子:

var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    var localSections = cfg.Sections.Cast<ConfigurationSection>() 
     .Where(s => s.SectionInformation.IsDeclared); 

最后,请注意,这种方法只会让你配置部分。它不会返回配置部分,它本身在<sectionGroup>之内。对于他们,您首先需要遍历Configuration.SectionGroups,它拥有自己的Sections -property,其中包含每个部分组部分。它也可以包含嵌套的部分组,可通过每个ConfigurationSectionGroup实例的SectionGroups属性再次访问。

+0

谢谢。这似乎正是我需要的。干杯! – bornfromanegg 2012-04-26 13:00:10

0

,如果把所有的段成段组这会工作:

<configSections> 
     <sectionGroup name="FMGlobal.Common.SecuritySubsystem.ADAzManFeed"> 
     <section name="ADFolders" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
     </sectionGroup> 
    </configSections> 

    var NVC = (ConfigurationManager.GetSection(_ 
    "FMGlobal.Common.SecuritySubsystem.ADAzManFeed")