我想制作一个看起来像这样的 app.config
<configuration>
<SQLconneciton>
<add key=name/>
<add key= otherStuff/>
</SQLconnection>
<PacConnection>
<add key=name/>
<add key= otherStuff/>
</PacConnection>
</configuration>
我读过很多示例,其中人们创建一个自定义部分并添加内容,我需要允许用户添加多个部分、读取、删除。我真的不需要花哨的元素,只需要简单的添加和键值。分区组值得使用还是我遗漏了一些简单的东西?
最佳答案
当然 - 没有什么能阻止您创建任意数量的自定义配置部分!
尝试这样的事情:
<?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 定义的现有节处理程序类型以及您自己的自定义配置节,如果您自己定义了其中一些 - 只需使用您需要的任何东西!
关于c# - 向 App Config C# 添加多个自定义部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14147080/