首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何获取NameValueSectionHandler类型的ConfigurationSection的值

如何获取NameValueSectionHandler类型的ConfigurationSection的值
EN

Stack Overflow用户
提问于 2010-08-12 02:03:28
回答 8查看 118.9K关注 0票数 67

我正在使用C#,Framework3.5(VS2008)。

我使用ConfigurationManager将配置(而不是默认的app.config文件)加载到配置对象中。

使用Configuration类,我能够获得一个ConfigurationSection,但是我找不到一种方法来获得该部分的值。

在配置中,ConfigurationSection的类型为System.Configuration.NameValueSectionHandler

无论如何,当我使用ConfigurationManager的方法GetSection (仅当它在我的默认app.config文件上时才起作用)时,我收到了一个对象类型,我可以将其转换为键值对的集合,而我只是像字典一样接收到了这个值。但是,当我从Configuration类接收到ConfigurationSection类时,我无法进行这样的强制转换。

编辑:配置文件示例:

代码语言:javascript
复制
<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 ):

代码语言:javascript
复制
NameValueCollection myParamsCollection =
             (NameValueCollection)ConfigurationManager.GetSection("MyParams");

Console.WriteLine(myParamsCollection["FirstParam"]);
Console.WriteLine(myParamsCollection["SecondParam"]);
EN

回答 8

Stack Overflow用户

发布于 2013-03-04 23:00:45

受到确切问题的困扰。问题是由于.config文件中的NameValueSectionHandler引起的。您应该改用AppSettingsSection:

代码语言:javascript
复制
<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#代码中:

代码语言:javascript
复制
AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");

顺便说一句,2.0中不再支持NameValueSectionHandler。

票数 27
EN

Stack Overflow用户

发布于 2010-08-12 02:53:18

Here's上有一篇很好的文章,展示了如何做到这一点。

如果要从app.config以外的文件中读取值,则需要将其加载到ConfigurationManager中。

试试这个方法:ConfigurationManager.OpenMappedExeConfiguration()

在MSDN文章中有一个如何使用它的示例。

票数 18
EN

Stack Overflow用户

发布于 2013-01-18 01:27:55

尝试使用AppSettingsSection而不是NameValueCollection。如下所示:

代码语言:javascript
复制
var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;

来源:http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d5079420-40cb-4255-9b3b-f9a41a1f7ad2/

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3461418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档