我正在使用通过控制台应用程序创建的app.config文件,我可以使用.读取key1的val1 ConfigurationSettings.AppSettings["key1"].ToString()
<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>
Run Code Online (Sandbox Code Playgroud)
但我有太多的键和值,我想让它们分类.
我发现在我的应用程序中很难使用的东西,因为我想以与上面类似的方式访问密钥
例如,我想做什么:
<appSettings>
<Section1>
<add key="key1" value="val1" />
</Section1>
<Section2>
<add key="key1" value="val1" />
<Section2>
</appSettings>
Run Code Online (Sandbox Code Playgroud)
如果有办法使用它来访问它
ConfigurationSettings.AppSettings["Section1"].["key1"].ToString()
Kon*_*ina 72
您可以在app.config中添加自定义部分,而无需编写其他代码.您所要做的就是在这样的configSections节点中"声明"新部分
<configSections>
<section name="genericAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
Run Code Online (Sandbox Code Playgroud)
然后你可以定义这个部分用键和值填充它:
<genericAppSettings>
<add key="testkey" value="generic" />
<add key="another" value="testvalue" />
</genericAppSettings>
Run Code Online (Sandbox Code Playgroud)
要从此部分获取密钥的值,您必须添加System.Configurationdll作为项目的引用,添加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"];
}
}
}
Run Code Online (Sandbox Code Playgroud)
好的一点是,如果需要,您可以轻松地制作一组部分:
<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>
Run Code Online (Sandbox Code Playgroud)
如果您使用组,要访问部分,您必须使用以下{group name}/{section name}格式访问它们:
NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("customAppSettingsGroup/genericAppSettings");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29785 次 |
| 最近记录: |