每一個網站裏都會有一個web.config文件。修改Web.config文件會致使IIS重啓,就是隨意的回車一下也會致使重啓。微軟建議,不要將須要修改的配置內容保存在web.config中。而是單獨放在一個config中。 web
可是對於單獨存放的config文件,怎麼來對其進行修改和讀取呢? 例如 能夠指定 web.config 中的 appSetting 單獨放在 一個 app-1.config 文件中。經過 configSource 來指定。 c#
1、原來的web.config文件: app
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="CacheTimeInfo" value="30" /> <add key="CacheTimeNews" value="10" /> <add key="CacheTimeProduct" value="60" /> <add key="CacheTimeTrade" value="5" /> <add key="SiteName" value="oschina"/> <add key="SiteDomain" value="oschina.net"/> </appSettings> <connectionStrings/> <system.web> <compilation debug="false"> </compilation> <authentication mode="Windows" /> </system.web> </configuration>
下面拆分紅兩個config文件 網站
1)第一個config文件:web.config this
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings configSource="app-1.config" /> <connectionStrings/> <system.web> <compilation debug="false"> </compilation> <authentication mode="Windows" /> </system.web> </configuration>
<?xml version="1.0" encoding="utf-8"?> <appSettings> <add key="CacheTimeInfo" value="30" /> <add key="CacheTimeNews" value="10" /> <add key="CacheTimeProduct" value="60" /> <add key="CacheTimeTrade" value="5" /> <add key="SiteName" value="oschina"/> <add key="SiteDomain" value="oscina.net"/> </appSettings>
那麼如何讀取呢? spa
Configuration config =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
string SiteName = config.AppSettings["SiteName"];
//若是用上面這種方法會報錯: CS0122: 「System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty]」不可訪問, 由於它受保護級別限制
正確的讀取方法是: .net
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); string SiteName = config.AppSettings.Settings["SiteName"].Value;
修改Config值: debug
Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); AppSettingsSection appSetting = cfg.AppSettings; appSetting.Settings["SiteName"].Value = "changed by application"; //修改config.config中SiteName的值 cfg.Save();
總結:通過拆分後,修改config.config不會致使IIS重啓。 說明:個人app-1.config文件和webconfig在同一級目錄,另外,我這裏叫app-1.config,你能夠隨意改變,好比叫app.config。 注意app-1.config的寫法。 一旦在web.config中的appSettings節點中添加configSource,就不能再添加Add節點了。也就是說你不能在webconfig裏放一部分<add>,而後再config.config裏在放一部分<add> 修改時,訪問的節點必須存在不然會報:未將對象引用設置到對象的實例。