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; //修改某键值配置