.net1.1中如果需要靈活的操作和讀寫配置文件并不是十分方便,一般都會在項目中封裝一個配置文件管理類來進行讀寫操作。而在.net2.0中使用ConfigurationManager 和WebConfigurationManager 類可以很好的管理配置文件,ConfigurationManager類在System.Configuration中,WebConfigurationManager在System.Web.Configuration中。根據(jù)MSDN的解釋,對于 Web 應(yīng)用程序配置,建議使用 System.Web.Configuration.WebConfigurationManager 類,而不要使用 System.Configuration.ConfigurationManager 類。
下面我給出一個簡單的例子說明如何使用WebConfigurationManager操作配置文件:
//打開配置文件
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
//獲取appSettings節(jié)點
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
//在appSettings節(jié)點中添加元素
appSection.Settings.Add("addkey1", "key1's value");
appSection.Settings.Add("addkey2", "key2's value");
config.Save();
運行代碼之后可以看見配置文件中的改變:
<appSettings>
<add key="addkey1" value="key1's value" />
<add key="addkey2" value="key2's value" />
</appSettings>
修改和刪除節(jié)點或?qū)傩砸卜浅7奖悖?/P>
//打開配置文件
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
//獲取appSettings節(jié)點
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
//刪除appSettings節(jié)點中的元素
appSection.Settings.Remove("addkey1");
//修改appSettings節(jié)點中的元素
appSection.Settings["addkey2"].Value = "Modify key2's value";
config.Save();
配置文件:
<appSettings>
<add key="addkey2" value="Modify key2's value" />
</appSettings>
參考:http://msdn2.microsoft.com/en-us/library/ms228060.aspx
http://justicfu.VEVb.com/archive/2006/06/21/431632.html
新聞熱點
疑難解答