您的位置:首页 > 编程语言 > ASP

为asp.net程序添加自定义配置区域 (转)

2005-03-14 08:19 525 查看
我们通常把诸如sql的connection string之类的配置信息保存在web.config的AppSettings部分,以方便程序的分发,并且可以通过以下方法在程序中获得:
string sqlStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];

对于结构比较复杂的自定义配置,可以通过实现IConfigurationSectionHandler接口来实现这种机制。首先,创建MySettings类,该类仅包含了我需要的一些自定义配置的定义:

using System;

namespace myconfig
using System;
using System.Configuration;
using System.Xml;

namespace myconfig
<configSections>
<section name="MySettings" type="myconfig.MyConfigHandler,myconfig"></section>
</configSections>

<MySettings>
<SomeSetting>This is a customer configuration setting.</SomeSetting>
</MySettings>

其中<configSecions>告诉web.config调用MyConfigHandler来处理MySettings,<MySettings>中保存的就是自定义的配置内容,例如在某个web page中执行如下代码:

private void Page_Load(object sender, System.EventArgs e)
// Put user code to initialize the page here
MySettings myset;
myset = System.Configuration.ConfigurationSettings.GetConfig("MySettings") as MySettings;

Response.Write(myset.SomeSetting);
}

得到的结果将会是在客户端显示This is a customer configuration setting。其实还有另一种更简单的方法,就是利用NameValueFileSectionHandler,但是在添加配置信息时需要像在AppSettings中那样用<add name="" value=""></add>来添加键值,对于自定义配置来说意义不大,具体可以参考msdn中相关的文章。

原文: http://www.cnblogs.com/roger/archive/2004/11/02/59788.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: