您可以在 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");