c# ConfigurationSection

使用ConfigurationSection自定义配置节点

实现IConfigurationSectionHandler接口可处理自定义节点,IConfigurationSectionHandler在. net Framework 2.0及以上版本中已弃用,但是,因为它是内部使用的,所以任然可用,但不建议用,毕竟人家已弃用。在. net Framework 2.0及以上版本中,您必须从ConfigurationSection类派生来实现相关的配置节处理程序。
我们有两种模型创建自定义配置,编程或声明式(带属性)模型。以下示例使用声明式模型实现。

对如下配置文件实现处理程序并获取配置内容。

<configuration>
	<!-- 配置节处理程序的声明区。 -->
	<configSections>
		<sectionGroup name="log">
			<section name="logging" type="ConsoleApp.LoggingSection, ConsoleApp" />
		</sectionGroup>
		<!-- 其他的 <section> 和 <sectionGroup> 元素。 -->
	</configSections>
	<!-- 配置节的设定区。 -->
	<log>
		<logging type="file">
			<logAdapter type="ConsoleOutLogger, ConsoleApp">
				<arg key="showLogName" value="true" />
				<arg key="showDataTime" value="true" />
				<arg key="level" value="ALL" />
				<arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:SSS" />
			</logAdapter>
		</logging>
	</log>
</configuration>

准备工作

  1. 环境:vs2022;.net6
  2. nuget安装System.Configuration.ConfigurationManager
  3. using System.Configuration;

示例

首先定义节点处理程序,从配置文件可以看到,配置节名称为logging,处理类为ConsoleApp.LoggingSection(<section name="logging" type="ConsoleApp.LoggingSection, ConsoleApp" />),从配置节设置区,可以看到logging元素有一个属性为type,有一个子元素logAdapter,如下示例:

 namespace ConsoleApp
{
    public class LoggingSection : ConfigurationSection
    {
        [ConfigurationProperty("type")]
        public string Type
        {
            get { return (string)base["type"]; }
            set { base["type"] = value; }
        }

        [ConfigurationProperty("logAdapter")]
        public LogAdapterEelement LogAdapter
        {
            get { return (LogAdapterEelement)base["logAdapter"]; } 
            set { base["logAdapter"] = value; }
        }
    }
}

定义子元素logAdapter的处理类LogAdapterEelement(继承自ConfigurationElement),子元素logAdapter包含一个属性type,还有一个arg元素的集合(没有对应元素的集合,即没有name)

namespace ConsoleApp
{
    public class LogAdapterEelement : ConfigurationElement
    {
        [ConfigurationProperty("type")]
        public string Type
        {
            get { return (string)base["type"];}
            set { base["type"] = value;}
        }

        [ConfigurationProperty("", IsDefaultCollection = true)]
        public ArgElementCollection ArgElements
        {
            get { return (ArgElementCollection)base[""]; }
        }
    }
}

实现arg元素集合(继承自ConfigurationElementCollection)

namespace ConsoleApp
{
    public class ArgElementCollection : ConfigurationElementCollection
    {
        //ConfigurationElementCollection的抽象方法,必须实现
        protected override ConfigurationElement CreateNewElement()
        {
            return new ArgElement();    
        }

        //ConfigurationElementCollection的抽象方法,必须实现
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ArgElement)element).Key;
        }

        //指定集合类型
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }

        //定义集合元素对应的xml元素
        protected override string ElementName
        {
            get
            {
                return "arg";
            }
        }

        //获取集合元素
        public ArgElement this[int index]
        {
            get
            {
                return (ArgElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
    }
}

实现元素arg,元素arg包两个属性,分为key和value。

namespace ConsoleApp
{
    public class ArgElement : ConfigurationElement
    {
        [ConfigurationProperty("key",IsKey =true)]
        public string Key 
        {
            get { return (string)base["key"]; }
            set { base["key"] = value; }
        }

        [ConfigurationProperty("value")]
        public string Value
        {
            get { return (string)base["value"]; }
            set { base["value"] = value; }
        }
    }
}

获取配置内容

LoggingSection config = (LoggingSection)System.Configuration.ConfigurationManager.GetSection("log/logging");

当在运行时调用GetSection方法时,配置系统首先创建ConfigurationSection类的实例,然后返回它从GetRuntimeObject方法获得的对象。默认情况下,GetRuntimeObject只是返回表示调用它的ConfigurationSection的对象。所以通过重新(override )GetRuntimeObject方法,可以自定义GetSection的返回类型。
重新修改LoggingSection 类,添加GetRuntimeObject的重新方法

 namespace ConsoleApp
{
    public class LoggingSection : ConfigurationSection
    {
        [ConfigurationProperty("type")]
        public string Type
        {
            get { return (string)base["type"]; }
            set { base["type"] = value; }
        }

        [ConfigurationProperty("logAdapter")]
        public LogAdapterEelement LogAdapter
        {
            get { return (LogAdapterEelement)base["logAdapter"]; } 
            set { base["logAdapter"] = value; }
        }
        
        protected override object GetRuntimeObject()
        {
            return this.LogAdapter;
        }
    }
}

获取自定义返回值

LogAdapterEelement config = (LogAdapterEelement)System.Configuration.ConfigurationManager.GetSection("log/logging");

参考:

https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationsection?redirectedfrom=MSDN&view=dotnet-plat-ext-7.0
https://learn.microsoft.com/en-us/previous-versions/aspnet/2tw134k3(v=vs.100)
https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationelementcollection?redirectedfrom=MSDN&view=dotnet-plat-ext-7.0
https://www.cnblogs.com/aspnethot/articles/1408689.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ts16dmy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值