dotNET中创建自定义的配置节
自定义节的配置文件 myCustom.config 如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomSection" type="CustomConfig.MyCustomSection, CustomConfig"/>
</configSections>
<myCustomSection myFirstSetting="1" mySecondSetting="A" />
</configuration>
其中 section 节的书写格式:
<section name="section name"
type="configuration section handler class, assembly file name, version, culture, public key token"
allowDefinition= "Everywhere|MachineOnly|MachineToApplication|MachineToWebRoot"
allowLocation="True|False"
restartOnExternalChanges="True|False" />
关于configSections 的 section 元素(常规设置架构)请参考
http://msdn.microsoft.com/zh-cn/library/ms228245(VS.80).aspx 中有较详细的解释。
那么,我们如何来通过程序读取自定义的配置参数及值呢?其实很简单我们只需要从ConfigurationSection 派生出自己的类即可。程序如下:
using System.Configuration;
namespace CustomConfig
{
public sealed class MyCustomSection : ConfigurationSection
{
public MyCustomSection(){
}
[ConfigurationProperty("myFirstSetting")]
public long MyFirstSetting
{
get
{
return (long)this["myFirstSetting"];
}
set
{
this["myFirstSetting"] = value;
}
}
[ConfigurationProperty("mySecondSetting")]
public string MySecondSetting
{
get{
return (string)this["mySecondSetting"];
}
set{
this["mySecondSetting"] = value;
}
}
}
}
仅需要在表示配置节的属性的前边加上ConfigurationProperty 属性标记即可。
测试程序如下:
static void Main(string[] args)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"myCustom.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(
fileMap, ConfigurationUserLevel.None);
MyCustomSection section = config.Sections["myCustomSection"] as MyCustomSection;
if (section != null)
{
Console.WriteLine("My first Setting: {0}", section.MyFirstSetting);
Console.WriteLine("My second setting: {0}", section.MySecondSetting);
}
Console.ReadKey();
}
程序输出:
My first Setting: 1
My second setting: A
在属性标记中还可以设置默认值、最小值、最大值等等。如:
[ConfigurationProperty("myFirstSetting", DefaultValue = (long)1, IsRequired = true)]
[LongValidator(MinValue = 1, MaxValue = 10000, ExcludeRange = false)]
设置 myFirstSetting 的默认值是1 且是必须的。LongValidator 设置配置文件中值的范围只能是在[1-10000]之间。
[ConfigurationProperty("mySecondSetting", DefaultValue="A",IsRequired=true)]
[StringValidator(InvalidCharacters="~!@#$%^&*(){}/;'|\\",MinLength=1,MaxLength=60)]
StringValidator中设置有无效的字符及字符串的长度。
代码文件:
Xing 学习笔记 2008-6-24整理