我有一个关于从 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/