中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 数据库开发 > 数据库综合
web.config文件自定义配置节的使用方法的一个简单例子
作者:未知 时间:2004-10-11 12:12 出处:Blog 责编:chinaitpower
              摘要:暂无
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接口来读取配置

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有