2012-04-26 104 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")