数据库

本类阅读TOP10

·SQL语句导入导出大全
·Power Designer杂记
·SQL Server日期计算
·常用的oracle函数使用说明(一)
·sqlserver2000数据库置疑的解决方法
·MS SQLServer OLEDB分布式事务无法启动的一般解决方案
·SQL to Excel 的应用
·SQL语句导入导出大全
·Error:ORA-01033:ORACLE initialization or shutdown in progress错误解决
·Oracle中password file的作用及说明

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
web.config文件自定义配置节的使用方法的一个简单例子

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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接口来读取配置




相关文章

相关软件




月光软件程序下载编程文档电脑教程网站设计网址导航网络文学游戏天地幽默笑话生活休闲写作范文安妮宝贝
电脑技术编程开发网络专区谈天说地情感世界游戏元素分类游戏热门游戏体育运动手机专区业余爱好影视沙龙
音乐天地数码广场教育园地科学大观古今纵横谈股论金人文艺术医学保健动漫图酷二手专区地方风情各行各业

月光软件站·版权所有