您的位置:首页 > 其它

多个web.config如何管理

2008-05-04 17:05 204 查看
假设一个网站系统存在两个配置文件web.config和config.config,那么我如何读取config.config的配置节呢?System.Configuration名字空间下的接口好象只能读取web.config中的配置信息。
为什么要配置多个Config文件呢?主要为一下原因:
其一:如果我的配置节很多的话web.config会变得很大,不易管理和查找;
其二:程序运行后对web.config的改动会引起站点的重启,如果系统管理员修改配置文件也会引起系统站点重启,这样会影响系统的运行。
综合以上问题,微软建议:
不要将需要修改的配置内容保存在web.config中。而是单独放在一个config中。但是对于单独存放的config文件,怎么来对其进行修改和读取呢?

例如 可以指定 web.config 中的 appSetting 单独放在 一个 app.config 文件中。通过 configSource 来指定。
<configuration>
<appSettings c />

然后在 app.config 文件中加入 <appSettings> 中的内容如
<appSettings>
<add key="a" value="changed by application" />
</appSettings>

当 使用WebConfigurationManager的时候就会自动将app.config中的内容加入到web.config中,你可以通过 WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath).AppSettings 来读取 appSettings的内容。同样也可以修改appSettings中的内容,但是由于最终修改的是app.config文件,所以可以避免因修改 web.config而引起的restart 。
修改代码如下:
Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSetting = cfg.AppSettings;

//读取
string settingValue = appSetting.Settings["see"].Value;

//修改
appSetting.Settings["see"].Value = "changed by application";
cfg.Save();

web.config文件中:
<appSettings configSource="test.config"/>

test.config文件内容。
<appSettings>
<add key="see" value="changed by application" />
</appSettings>

如果新的config文件存在不同的文件夹下,如何处理?
web.config文件中:
<appSettings configSource="office//test.config"/>
test.config文件内容不变。

参考:test.config文件内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: