读取配置文件中的自定义节

用户可以在配置文件中添加自定义节,但添加的自定义节也必须由用户编写自定义类来读取,该自定义类必须实现IConfigurationSectionHandler 接口,一个简单的示例代码如下:

自定义类:
using  System;
using  System.Xml;
using  System.Collections;
using  System.Configuration;
using  System.Collections.Specialized; 

namespace  WebApp
{
    
/// <summary>
    
/// Summary description for MyConfiguration.
    
/// </summary>

    public class MyConfiguration : IConfigurationSectionHandler
    
{
        
public static string Name;
        
public static string Password;

        
public MyConfiguration()
        
{
            
        }


        
public Object Create(Object parent, object configContext, XmlNode section)
        
{
            NameValueCollection settings;
            
            
try
            
{
                NameValueSectionHandler baseHandler 
= new NameValueSectionHandler();
                settings 
= (NameValueCollection)baseHandler.Create(parent, configContext, section);
            }

            
catch
            
{
                settings 
= null;
            }

            
            
if ( settings == null )
            
{
                
            }

            
else
            
{
                Name 
= settings["Name"];
                Password 
= settings["Password"];
            }

            
return settings;
        }

    }

}

相应的配置文件:
<? xml version="1.0" encoding="utf-8"  ?>
< configuration >
    
< configSections >
            
< section  name ="WebAppConfiguration"  type ="WebApp.MyConfiguration, WebApp"   />
    
</ configSections >
    
    
< WebAppConfiguration >
        
< add  key ="Name"  value ="root"   />
        
< add  key ="Password"  value ="MyRoot"   />
    
</ WebAppConfiguration >
</ configuration >

读取配置文件的示例代码:
private   void  Page_Load( object  sender, System.EventArgs e)
        
{
            System.Configuration.ConfigurationSettings.GetConfig(
"WebAppConfiguration");
            Response.Write(MyConfiguration.Name 
+ "," + MyConfiguration.Password);
        }

说明: 在System.Configuration.ConfigurationSettings.GetConfig("WebAppConfiguration");语句被执行时,MyConfiguration类的Creat方法将被Framework自动调用,MyConfiguration.Name和MyConfiguration.Password的值被修改.

你可能感兴趣的:(读取配置文件)