我正在使用 C#、Framework 3.5 (VS 2008)。
我正在使用ConfigurationManager
将配置(不是默认的 app.config 文件)加载到 Configuration 对象中。
使用 Configuration 类,我能够得到ConfigurationSection
,但我找不到获取该部分的值的方法。
在配置中,ConfigurationSection
属于类型System.Configuration.NameValueSectionHandler
.
不管怎样,当我使用这个方法时GetSection
of the ConfigurationManager
(仅当它位于我的默认 app.config 文件中时才有效),我收到了一个对象类型,我可以将其转换为键值对的集合,并且我刚刚收到了像字典一样的值。当我收到时我不能做这样的演员ConfigurationSection
然而,来自 Configuration 类的类。
编辑:
配置文件示例:
<configuration>
<configSections>
<section name="MyParams"
type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MyParams>
<add key="FirstParam" value="One"/>
<add key="SecondParam" value="Two"/>
</MyParams>
</configuration>
我在 app.config 上使用它的方式示例(“GetSection”方法仅适用于默认 app.config):
NameValueCollection myParamsCollection =
(NameValueCollection)ConfigurationManager.GetSection("MyParams");
Console.WriteLine(myParamsCollection["FirstParam"]);
Console.WriteLine(myParamsCollection["SecondParam"]);
遇到了确切的问题。问题是由于 .config 文件中的 NameValueSectionHandler 造成的。您应该使用 AppSettingsSection 代替:
<configuration>
<configSections>
<section name="DEV" type="System.Configuration.AppSettingsSection" />
<section name="TEST" type="System.Configuration.AppSettingsSection" />
</configSections>
<TEST>
<add key="key" value="value1" />
</TEST>
<DEV>
<add key="key" value="value2" />
</DEV>
</configuration>
然后在 C# 代码中:
AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");
顺便说一句,2.0 中不再支持 NameValueSectionHandler。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)