private static string _PortName; public static string PortName { get { //如果配置信息已读到内存则下次不需要再从文件中读了,修改配置也只需要修改内存中的值 if (!string.IsNullOrEmpty(_PortName)) return _PortName; try { _PortName = ConfigurationManager.AppSettings["PortName"].ToString(); return _PortName; } catch (Exception ex) { throw ex; } } set { //更新缓存,下次直接读缓存 _PortName = value; //持久化到文件 SetConfig("PortName", value); } } public static void SetConfig(string key, string value) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config.AppSettings.Settings[key] != null) config.AppSettings.Settings[key].Value = value; else config.AppSettings.Settings.Add(key, value); config.Save(ConfigurationSaveMode.Modified); //刷新节点,这样下次检索时将从磁盘重新读取它 ConfigurationManager.RefreshSection("appSettings"); } catch (Exception ex) { throw ex; } }
AppConfig 操作简易封装
猜你喜欢
转载自www.cnblogs.com/hellowzl/p/9118267.html
今日推荐
周排行