C#自定义配置文件

.Net Framework 提供 System.Configuration 命名空间支持自定义配置文件,如 web.config 和 app.config。本文介绍如何创建自定义配置节,包括定义配置类、属性、以及访问配置的方法。内容涵盖简单配置、嵌套配置元素、配置集合、键值对配置以及SectionGroup的使用,为开发者提供灵活的配置管理方案。
摘要由CSDN通过智能技术生成

.Net中的System.Configuration命名空间为我们在web.config或者app.config中自定义配置提供了完美的支持。

如果你已经对自定义配置了如指掌,请忽略这篇文章。

言归正传,我们先来看一个最简单的自定义配置

?
<? xml  version = "1.0"  encoding = "utf-8"  ?>
< configuration >
   < configSections >
     < section  name = "simple"  type = "ConfigExample.Configuration.SimpleSection,ConfigExample" />
   </ configSections >
   < simple  maxValue = "20"  minValue = "1" ></ simple >
</ configuration >

在配置文件中使用自定义配置,需要在configSections中添加一个section元素,并制定此section元素对应的类型和名字。然后再在configuration根节点下面添加此自定义配置,如上例中的simple节点。simple节点只有两个整形数的属性maxValue和minValue。

要在程序中使用自定义配置我们还需要实现存取这个配置块的类型,一般需要做如下三件事:
1. 定义类型从System.Configuration.ConfigurationSection继承
2. 定义配置类的属性,这些属性需要用ConfigurationProperty特性修饰,并制定属性在配置节中的名称和其他一些限制信息
3. 通过基类的string索引器实现属性的get ,set

非常简单和自然,如下是上面配置类的实现:

?
public  class  SimpleSection:System.Configuration.ConfigurationSection
{
     [ConfigurationProperty( "maxValue" ,IsRequired= false ,DefaultValue=Int32.MaxValue)]
     public  int  MaxValue
     {
         get
         {
             return   ( int ) base [ "maxValue" ];
         }
         set
         {
             base [ "maxValue" ] = value;
         }
     }
 
     [ConfigurationProperty( "minValue" ,IsRequired= false ,DefaultValue=1)]
     public  int  MinValue
     {
         get  { return  ( int ) base [ "minValue" ];}
         set  { base [ "minValue" ] = value; }
     }
 
 
     [ConfigurationProperty( "enabled" ,IsRequired= false ,DefaultValue= true )]
     public  bool  Enable
     {
         get
         {
             return  ( bool ) base [ "enabled" ];
         }
         set
         {
             base [ "enabled" ] = value;
         }
     }
}

这样子一个简单的配置类就完成了,怎么在程序中使用这个配置呢?需要使用ConfigurationManager类(要引用System.configuration.dll这个dll只有在.Net2.0之后的版本中才有)的GetSection方法获得配置就可以了。如下代码:

?
SimpleSection simple = ConfigurationManager.GetSection( "simple" ) as  SimpleSection;
Console.WriteLine( "simple minValue={0} maxValue = {1}"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值