app-config-appsetting节点c#中的sub-appsettings
本文关键字:sub-appsettings 中的 节点 app-config-appsetting | 更新日期: 2023-09-27 17:58:50
我使用的是通过控制台应用程序创建的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>
但我有太多的键和值,我想把它们分类。
我发现一些东西很难在我的应用程序中使用,因为我想以类似于上面一个的方式访问密钥
显示所有节点,并且在不获取所有节点的情况下无法读取节点
例如我想做的事情:
<appSettings>
<Section1>
<add key="key1" value="val1" />
</Section1>
<Section2>
<add key="key1" value="val1" />
<Section2>
</appSettings>
如果有办法使用ConfigurationSettings.AppSettings["Section1"].["key1"].ToString()
您可以在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");
AFAIK您可以在appsettings之外实现自定义部分。例如,像Autofac和SpecFlow这样的框架使用这些会话来支持自己的配置模式。您可以查看MSDN的这篇文章来了解如何做到这一点。希望能有所帮助。