• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: | 推荐给好友 上一篇 | 下一篇

web.config文件自定义配置节的使用方法的一个简单例子

发布: 2007-7-02 11:08 | 作者: admin | 来源: | 查看: 21次 | 进入软件测试论坛讨论

领测软件测试网 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接口来读取配置

延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备2023014753号-2
技术支持和业务联系:info@testage.com.cn 电话:010-51297073

软件测试 | 领测国际ISTQBISTQB官网TMMiTMMi认证国际软件测试工程师认证领测软件测试网