为什么要配置多个Config文件呢?主要为一下原因:
其一:如果我的配置节很多的话web.config会变得很大,不易管理和查找;
其二:程序运行后对web.config的改动会引起站点的重启,如果系统管理员修改配置文件也会引起系统站点重启,这样会影响系统的运行。
综合以上问题,微软建议:
不要将需要修改的配置内容保存在web.config中。而是单独放在一个config中。但是对于单独存放的config文件,怎么来对其进行修改和读取呢?
例如 可以指定 web.config 中的 appSetting 单独放在 一个 WebAppSetting.config 文件中。通过 configSource 来指定。
<configuration>
<appSettings configSource="WebAppSetting.config"></appSettings>
</configuration>
然后在 WebAppSetting.config 文件中加入 <appSettings> 中的内容如
<appSettings>
<add key="see" value="changed by application" />
</appSettings>
当 使用WebConfigurationManager的时候就会自动将WebAppSetting.config中的内容加入到web.config中,你可以通过 WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath).AppSettings 来读取 appSettings的内容。同样也可以修改appSettings中的内容,但是由于最终修改的是WebAppSetting.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文件内容。
<?xml version="1.0" encoding="utf-8"?>
<add key="see" value="changed by application" />
</appSettings>
如果新的config文件存在不同的文件夹下,如何处理?
web.config文件中:
<appSettings configSource="office\\test.config"/>
test.config文件内容不变。
PS: 连接字符串的配置
web.config文件中:
<connectionStrings configSource="WebConnectionString.config"></connectionStrings>
WebConnectionString.config文件内容。
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
<add name="GlobalEyeDataLayer.Properties.Settings.GlobalEyeConnectionString"
connectionString="Data Source=. ;Initial Catalog=GlobalEye;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
<add name="ConnectionString2"
connectionString="Data Source=. ;Initial Catalog=JZQY;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
</connectionStrings>