web.config文件自定义配置节的使用方法的一个简单例子
来源:互联网 发布:sas编程难么 编辑:程序博客网 时间:2024/05/18 01:32
用来演示的程序名为MyApp,Namespace也是MyApp
1。编辑web.config文件
添加以下内容,声明一个Section
<section name="AppConfig" type="MyApp.AppConfig, MyApp" />
</configSections>
声明了一个叫AppConfig的Section
2。编辑web.config文件
添加以下内容,加入一个Section
<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接口来读取配置
- web.config文件自定义配置节的使用方法的一个简单例子
- web.config文件自定义配置节的使用方法的一个简单例子
- web.config文件自定义配置节的使用方法
- web.config文件自定义配置节的使用方法
- web.config文件自定义配置节的使用方法
- web.config文件自定义配置节的使用方法
- web.config文件自定义配置节的使用方法
- web.config文件自定义配置节的使用方法 (转)
- 一个简单的config配置例子
- web.config文件的配置
- 在web.config和app.config文件中增加自定义配置节点的方法
- 一个例子了解apacheBench的简单使用方法
- 一个修改web.config中appSettings配置节的函数
- 一个修改web.config中appSettings配置节的函数
- [Duwamish]读取web.config配置节的一个过程
- 一个修改web.config中appSettings配置节的函数
- 一个修改web.config中appSettings配置节的函数
- web.config文件的配置 作
- 留神MSN和QQ好友发送来的文件!!!
- .NET重要技术思考——原文在《程序员》杂志第六期
- 如何在WINDOWS 2000将ORALCE完全卸载
- 如何安装VS.NET2003中文版自带的QuickStart
- Hibernate和Spring对DAO处理的实例
- web.config文件自定义配置节的使用方法的一个简单例子
- 短信息发送
- 数据库连接字在Web.config里的用法
- 学习Struts+spring+hibernate的笔记
- Duwamish 7 初探——数据流程
- Duwamish深入剖析-配置篇
- Duwamish深入剖析-结构篇
- HTML文档中小meta的大作用[转自http://www.gccgle.com/2004-02/20040206233121.html]
- Robots Meta Tag的使用[ZZ:http://www.gccgle.com/2004-02/20040206233621.html]