appsetting node c#中的子appsettings

时间:2013-02-11 12:34:19

标签: c# app-config

我正在使用通过控制台应用程序创建的app.config文件,我可以使用ConfigurationSettings.AppSettings["key1"].ToString()

读取key1的val1
<configuration>  
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
    </startup>  
    <appSettings>
        <add key="key1" value="val1" />
        <add key="key2" value="val2" />  
    </appSettings> 
</configuration>

但我有太多的键和值,我想让它们分类。

我发现在我的应用程序中难以使用的东西,因为我想以与上述类似的方式访问密钥

Showing all nodes and can't read a node without getting all the nodes

例如我想做什么:

<appSettings>
    <Section1>
        <add key="key1" value="val1" />
    </Section1>
    <Section2>
        <add key="key1" value="val1" />
    <Section2>
</appSettings>

如果有办法使用它来访问它 ConfigurationSettings.AppSettings["Section1"].["key1"].ToString()

2 个答案:

答案 0 :(得分:67)

您可以在app.config中添加自定义部分,而无需编写其他代码。您所要做的就是在configSections节点中“声明”新部分

<configSections>
      <section name="genericAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>

然后你可以定义这个部分用键和值填充它:

  <genericAppSettings>
      <add key="testkey" value="generic" />
      <add key="another" value="testvalue" />
  </genericAppSettings>

要从此部分获取密钥的值,您必须添加System.Configuration dll作为项目的参考,添加using并使用GetSection方法。例如:

using System.Collections.Specialized;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("genericAppSettings");

            string a = test["another"];
        }
    }
}

好的一点是,如果您需要,您可以轻松制作一组章节:

<configSections>
    <sectionGroup name="customAppSettingsGroup">
      <section name="genericAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 // another sections
    </sectionGroup>
</configSections>

  <customAppSettingsGroup>
    <genericAppSettings>
      <add key="testkey" value="generic" />
      <add key="another" value="testvalue" />
    </genericAppSettings>
    // another sections
  </customAppSettingsGroup>

如果您使用群组,要访问部分,您必须使用{group name}/{section name}格式访问它们:

NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("customAppSettingsGroup/genericAppSettings");

答案 1 :(得分:0)

AFAIK您可以在appsettings之外实现自定义部分。例如,Autofac和SpecFlow等框架使用这些类型的会话来支持自己的配置模式。您可以查看this MSDN文章,了解如何执行此操作。希望有所帮助。