zoukankan      html  css  js  c++  java
  • web.config文件自定义配置节的使用方法的一个简单例子

    web.config文件自定义配置节的使用方法的一个简单例子
    用来演示的程序名为myapp,namespace也是myapp
     
    1.编辑web.config文件
     
    添加以下内容,声明一个section
     
    <configsections> 
       <section name="appconfig" type="myapp.appconfig, myapp" /> 
    </configsections>  
     
    声明了一个叫appconfig的section
     
    2.编辑web.config文件
     
    添加以下内容,加入一个section
     
    <appconfig>
      <add key="connectionstring" value="this is a connectionstring" /> 
      <add key="usercount" value="199" />
    </appconfig>
     
    这个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接口来读取配置




  • 相关阅读:
    作业01
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言I博客作业04
    C语言II博客作业04
    C语言II—作业03
    C语言II博客作业02
    C语言II博客作业01
  • 原文地址:https://www.cnblogs.com/weapon/p/2818415.html
Copyright © 2011-2022 走看看