下面是详解C#读取Appconfig中自定义的节点的完整攻略。
一、准备工作
在开始之前,需要先在App.config配置文件中定义自定义节点。可以按照以下格式添加:
<configuration>
<configSections>
<section name="customSection" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<customSection>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</customSection>
</configuration>
其中,customSection
是自定义节点的名称,key1
和key2
是自定义节点中的自定义键值对。
二、读取自定义节点的值
方法一:
可以使用ConfigurationManager
类的AppSettings
属性读取自定义节点的值。示例代码如下:
using System.Configuration;
// 读取自定义节点的值
string value1 = ConfigurationManager.AppSettings["customSection:key1"];
string value2 = ConfigurationManager.AppSettings["customSection:key2"];
方法二:
可以使用ConfigurationManager
类的GetSection
方法和CustomSection
类读取自定义节点的值。示例代码如下:
using System.Configuration;
// 获取自定义节点
CustomSection customSection = ConfigurationManager.GetSection("customSection") as CustomSection;
// 读取自定义节点的值
string value1 = customSection.Settings["key1"].Value;
string value2 = customSection.Settings["key2"].Value;
注意:使用这种方法需要创建一个CustomSection
类,并继承ConfigurationSection
类。具体的代码如下:
using System.Configuration;
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public KeyValueConfigurationCollection Settings
{
get { return (KeyValueConfigurationCollection)this[""]; }
set { this[""] = value; }
}
}
三、完整示例
下面给出一个完整的示例代码,包括定义自定义节点和读取自定义节点的值两部分。
定义自定义节点
<configuration>
<configSections>
<section name="customSection" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<customSection>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</customSection>
</configuration>
读取自定义节点的值
using System;
using System.Configuration;
public class Program
{
public static void Main(string[] args)
{
// 方法一:使用ConfigurationManager.AppSettings读取自定义节点的值
string value1 = ConfigurationManager.AppSettings["customSection:key1"];
string value2 = ConfigurationManager.AppSettings["customSection:key2"];
Console.WriteLine("Method 1:");
Console.WriteLine("key1={0}", value1);
Console.WriteLine("key2={0}", value2);
// 方法二:使用ConfigurationManager.GetSection和CustomSection类读取自定义节点的值
CustomSection customSection = ConfigurationManager.GetSection("customSection") as CustomSection;
string value3 = customSection.Settings["key1"].Value;
string value4 = customSection.Settings["key2"].Value;
Console.WriteLine("Method 2:");
Console.WriteLine("key1={0}", value3);
Console.WriteLine("key2={0}", value4);
Console.ReadLine();
}
}
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public KeyValueConfigurationCollection Settings
{
get { return (KeyValueConfigurationCollection)this[""]; }
set { this[""] = value; }
}
}
希望这份攻略能够对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解C#读取Appconfig中自定义的节点 - Python技术站