c# - 使用 ConfigurationManager 从 App.config 读取嵌套值

标签 c# app-config configurationmanager

我有一个关于从 App.config 检索值的问题通过 ConfigurationManager .

这是我的App.config 。我计划将这些值外包给 printers.config并通过 printerOverrides configSource="printers.config" /> 提取值.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
     <sectionGroup name="printerOverrides">
        <section name="host" type="System.Configuration.NameValueSectionHandler" />
      </sectionGroup>
      <section name="test" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>  

  <startup> 
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <printerOverrides>
    <host name="machine1">
      <add key="defaultPrinter" value="Overridden" />
    </host>
    <host name="machine2">
      <add key="defaultPrinter" value="Overridden" />
      <add key="otherSetting" value="OtherSettingValue" />
    </host>
  </printerOverrides>
  <test>
    <add key="key1" value="value1" />
  </test>
</configuration>

我能够从 <test> 获取值-此片段没有任何问题的部分:

var test = ConfigurationManager.GetSection("test") as NameValueCollection;
Debug.WriteLine(test["key1"]);

但是我无法通过以下方式从SectionGroup元素中的部分检索数据

var test = ConfigurationManager.GetSection("machine1") as NameValueCollection;
Debug.WriteLine(test["defaultPrinter"]);

或者

var test = ConfigurationManager.GetSection("printerOverrides/machine1") as NameValueCollection;
Debug.WriteLine(test["defaultprinter"]);

我的 XML 无效吗?或者我需要什么来获取SectionGroup内嵌套部分的值

最佳答案

尽管配置中的 XML 有效,但配置本身无效。

节组配置不支持重复元素(每个元素必须是唯一的并单独指定)。此外,host 元素不能有任何属性。

您可以(某种程度上)通过使用如下配置来实现您想要的目标:

<configSections>
  <sectionGroup name="printerOverrides">
    <section name="host1" type="System.Configuration.NameValueSectionHandler" />
    <section name="host2" type="System.Configuration.NameValueSectionHandler" />
  </sectionGroup>
</configSections>  

<printerOverrides>
  <host1>
    <add key="defaultPrinter" value="Overridden" />
  </host1>
  <host2>
    <add key="defaultPrinter" value="Overridden" />
    <add key="otherSetting" value="OtherSettingValue" />
  </host2>  
</printerOverrides> 

然后这将起作用:

var test = ConfigurationManager.GetSection("printerOverrides/host1") as NameValueCollection;
Debug.WriteLine(test["defaultprinter"]);

如果这不能满足您的需求,那么您将需要创建自定义配置节类。请参阅How to create custom config section in app.config?

关于c# - 使用 ConfigurationManager 从 App.config 读取嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33032304/

相关文章:

c# - app.config 自定义配置 - 'System.TypeInitializationException'

azure - 覆盖 Azure 网站中的 applicationSettings "MySite.Properties.Settings.MySetting"

c++ - MS Visual Studio Professional 2013 - C++ 为 32 位和 64 位操作系统编译单个可执行文件?

c# - 如何在linq中过滤集合的集合?

c# - 如何使用 .Net 让窗口保持在顶部?

c# - 将结构数组从 C# 传递到 Delphi

c# - 从不同的文件加载 wcf 主机配置

c# - C#HtmlAgilityPack选择主要节点

c# - 为什么 log4net 在配置之前创建一个空日志文件?

c# - 获取 64 位版本的 machine.config