【问题标题】:Add More than One Custom Sections to App Config C#?向 App Config C# 添加多个自定义部分?
【发布时间】:2012-12-18 07:08:36
【问题描述】:
我想做一个看起来像这样的 app.config
<configuration>
<SQLconneciton>
<add key=name/>
<add key= otherStuff/>
</SQLconnection>
<PacConnection>
<add key=name/>
<add key= otherStuff/>
</PacConnection>
</configuration>
我已经阅读了许多人们制作一个自定义部分并添加内容的示例,我需要允许用户添加多个部分、阅读、删除。我真的不需要花哨的元素,只需要简单的添加和键值。部分组值得使用还是我缺少一些简单的东西?
【问题讨论】:
标签:
c#
asp.net
configuration
【解决方案1】:
当然 - 没有什么能阻止您创建任意数量的自定义配置部分!
试试这样的:
<?xml version="1.0"?>
<configuration>
<!-- define the config sections (and possibly section groups) you want in your config file -->
<configSections>
<section name="SqlConnection" type="System.Configuration.NameValueSectionHandler"/>
<section name="PacConnection" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<!-- "implement" those config sections as defined above -->
<SqlConnection>
<add key="abc" value="123" />
</SqlConnection>
<PacConnection>
<add key="abc" value="234" />
</PacConnection>
</configuration>
System.Configuration.NameValueSectionHandler 是用于包含<add key="...." value="....." /> 条目(如<appSettings>)的配置部分的默认类型。
要获取值,只需使用以下内容:
NameValueCollection sqlConnConfig = ConfigurationManager.GetSection("SqlConnection") as NameValueCollection;
string valueForAbc = sqlConnConfig["abc"];
如果您自己定义了其中一些,您可以完全混合和匹配 .NET 定义的现有节处理程序类型以及您自己的自定义配置节 - 只需使用您需要的任何内容!