简单实现自定义配置节1

时间:2022-05-23 16:09:10
       在程序中经常要使用自定义配置节来存储一些信息,下面是一个只读简单实现:
using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Configuration;

namespace  SmsWinForm
{

    
public   class  SectionHandler : System.Configuration.IConfigurationSectionHandler
    {
        
public   object  Create( object  parent,  object  configContext, System.Xml.XmlNode section)
        {
            
return   new  Config(section);
        }
    }

    
class  Config
    {
        
private  System.Xml.XmlNode m_section;

        
public  Config(System.Xml.XmlNode node)
        {
            m_section 
=  node;
        }

        
static   private  Config configSection
        {
            
get
            {
                Config config 
=  (Config)System.Configuration.ConfigurationManager.GetSection( " SmsWinForm " );
                
if  (config  ==   null )
                {
                    
throw   new  ApplicationException( " Failed to get configuration from App.config. " );
                }
                
return  config;
            }
        }

        
public   string   this [ string  key]
        {
            
get
            {
                System.Xml.XmlNode node 
=  m_section.SelectSingleNode(key);
                
if  (node  !=   null )
                    
return  node.InnerText;
                
else
                    
return   null ;
            }
        }

        
static   public   string  BoardID
        {
            
get
            {
                
return  configSection[ " boardid " ];
            }
        }

        
static   public   string  CategoryID
        {
            
get
            {
                
return  configSection[ " categoryid " ];
            }
        }

    }
}

App.config中
<? xml version="1.0" encoding="utf-8"  ?>
< configuration >
  
< configSections >
    
< section  name ="SmsWinForm"  type ="SmsWinForm.SectionHandler,ConsoleTest1" />
  
</ configSections >
  
< SmsWinForm >
    
< categoryid > CMPP </ categoryid >
    
< boardid > 32 </ boardid >
  
</ SmsWinForm >
</ configuration >

简单实现自定义配置节1简单实现自定义配置节1调用


Tip:如果只是用于只读情况下,那这个方法足够了,并且大部分情况我们很少更新配置节。

http://wintersun.cnblogs.com