c# 操作.config中AppSettings配置節


ConfigurationSettings.AppSettings[key].ToString();

這種方式很眼熟吧?

不過這種方式基本過時了,雖然還能用。

 

微軟建議采用ConfigurationManager類操作該配置節點:

var cfg= ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //打開配置文件

cfg.AppSettings.Settings.Add("key", "value"); //添加配置節

cfg.AppSettings.Settings["key"].Value = "value"; //修改配置節

cfg.AppSettings.Settings.Remove("key"); //刪除配置節

cfg.Save(); //保存

ConfigurationManager.RefreshSection("appSettings"); //更新緩存

針對RefreshSection特別說一下:

如果采用傳統的方式,修改了配置文件后,讀取的依然是緩存中的,不是最新的

有了這句話,就是修改了配置文件后,更新緩存,這樣不重啟系統,也能讀取到最新的配置。

 

順便介紹一下Web.config的操作方式:

 

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 

//其實這里微軟建議采用as操作符轉換 config.GetSection("appSettings") as AppSettingsSection;   

AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");             

appsection.Settings[key].Value;  //讀取某鍵值配置

appsection.Settings[key].Value = value; //修改某鍵值配置

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM