我正在使用C#,Framework3.5(VS2008)。
我使用ConfigurationManager
将配置(而不是默认的app.config文件)加载到配置对象中。
使用Configuration类,我能够获得一个ConfigurationSection
,但是我找不到一种方法来获得该部分的值。
在配置中,ConfigurationSection
的类型为System.Configuration.NameValueSectionHandler
。
无论如何,当我使用ConfigurationManager
的方法GetSection
(仅当它在我的默认app.config文件上时才起作用)时,我收到了一个对象类型,我可以将其转换为键值对的集合,而我只是像字典一样接收到了这个值。但是,当我从Configuration类接收到ConfigurationSection
类时,我无法进行这样的强制转换。
编辑:配置文件示例:
<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"]);
发布于 2013-03-04 23:00:45
受到确切问题的困扰。问题是由于.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。
发布于 2010-08-12 02:53:18
Here's上有一篇很好的文章,展示了如何做到这一点。
如果要从app.config以外的文件中读取值,则需要将其加载到ConfigurationManager中。
试试这个方法:ConfigurationManager.OpenMappedExeConfiguration()
在MSDN文章中有一个如何使用它的示例。
发布于 2013-01-18 01:27:55
尝试使用AppSettingsSection
而不是NameValueCollection
。如下所示:
var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
https://stackoverflow.com/questions/3461418
复制相似问题