C#自定义配置文件节的实现

时间:2022-08-30 20:52:39

1.配置文件:(注意configSections必须放在最上面否则会报错)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="UserDefinedConfiguration" type="ConsoleApplication9.UserDefinedConfiguration,ConsoleApplication9, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
allowLocation="true"
allowDefinition="Everywhere"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<UserDefinedConfiguration id="12" name="hecong" firstProperty="property2">
<myChildSection url="www.163.com" addr="不知道"></myChildSection><!--子节点-->
</UserDefinedConfiguration>
</configuration>

 2.配置文件的主类型也就是配置文件section中type所标记的类(注意应用configuration,dll):

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
/// <summary>
/// 自定义配置文件节点类型
/// </summary>
public class UserDefinedConfiguration: ConfigurationSection
{
private static UserDefinedConfiguration setting;
public static UserDefinedConfiguration Setting
{
get
{
if (setting == null)
setting
= (UserDefinedConfiguration)ConfigurationManager.GetSection("UserDefinedConfiguration");
return setting;
}
}

[ConfigurationProperty(
"id", DefaultValue = "1", IsRequired = true)]
[StringValidator(InvalidCharacters
= "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]//这个属性只是不出现引号中的字符
public long Id
{
get { return (long)this["id"]; }
set { this["id"] = value; }
}

[ConfigurationProperty(
"name", DefaultValue = "Lily", IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}

[ConfigurationProperty(
"firstProperty", DefaultValue = "Property1", IsRequired = true)]
public string FirstProperty
{
get { return (string)this["firstProperty"]; }
set { this["firstProperty"] = value; }
}

[ConfigurationProperty(
"myChildSection")]
public UrlConfigurationElement MyChildSection//子节点
{
get
{
return (UrlConfigurationElement)this["myChildSection"]; }
set
{
this["myChildSection"] = value; }
}
}
}

3.子节点类型:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
public class UrlConfigurationElement: ConfigurationElement
{
[ConfigurationProperty(
"url", DefaultValue = "www.baidu.com", IsRequired = true)]
public string Url
{
get { return (string)this["url"]; }
set { this["url"] = value; }
}

[ConfigurationProperty(
"addr", DefaultValue = "Lily", IsRequired = true)]
public string Addr
{
get { return (string)this["addr"]; }
set { this["addr"] = value; }
}
}
}

4.后续添加key,value 和多个add节点