Username: Password:

web.config文档自定义配置节的使用方法的一个简单例子-数据库专栏,SQL Server
来源:作者: 发布时间:2007-12-25 13:48:11

web.config文档自定义配置节的使用方法的一个简单例子
用来演示的程式名为myapp,namespace也是myapp

1。编辑web.config文档

添加以下内容,声明一个section


  

  

声明了一个叫appconfig的section

2。编辑web.config文档

添加以下内容,加入一个section


  
  
 

这个section包括两个 key

3。从iconfigurationsectionhandler派生一个类,appconfig

实现create方法,代码如下

public class appconfig : iconfigurationsectionhandler
{
  static string m_connectionstring = string.empty;
  static int32 m_usercount = 0;
  public static string connectionstring
  {
   get
   {
    return m_connectionstring;
   }
  }
  public static int32 usercount
  {
   get
   {
    return m_usercount;
   }
  }

  static string readsetting(namevaluecollection nvc, string key, string defaultvalue)
  {
   string thevalue = nvc[key];
   if(thevalue == string.empty)
    return defaultvalue;

   return thevalue;
  }

  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 )
   {
    m_connectionstring = appconfig.readsetting(settings, "connectionstring", string.empty);
    m_usercount = convert.toint32(appconfig.readsetting(settings, "usercount", "0"));
   }
  
   return settings;
  }
}

我们把任何的配置都映射成相应的静态成员变量,并且是写成只读属性,这样程式通过

类似appconfig.connectionstring就能够访问,配置文档中的项目了

4。最后还要做一件事情

在global.asax.cs中的application_start中添加以下代码

system.configuration.configurationsettings.getconfig("appconfig");

这样在程式启动后,会读取appconfig这个section中的值,系统会调用您自己实现的iconfigurationsectionhandler接口来读取配置

喜欢本文,那就收藏到:

    Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网
相关评论  我也要评论
还没有关于此文章的相关评论!
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
  • 导航
    赞助商
    文章类别
    订阅