很多时候我们需要对系统的.config文件进度读写操作,例如:系统初始化的参数的更改、系统参数的改变都需要更新到配置文件。
首先我们有必要了解一下app.config、exe.config和vshost.exe.config作用和区别:
vshost.exe.config是程序运行时的配置文本,exe.config是程序运行后会复制到vshost.exe.config,app.config是在vshost.exe.config和exe.config没有情况起作用,从app.config复制到exe.config再复制到vshost.exe.config。vshost.exe.config和exe.config会自动创建内容跟app.config一样。了解过这些其实写配置文件都是写到exe.config文件中了,app.config不会变化。网上也有许多关于配置文件的读写操作,也是借鉴了多位前辈的经验自己总结的一些比较常用的读写操作。废话不多说,直接上主题:
- appSetting节点
修改或新增AppSetting节点
1 /// <summary> 2 /// 修改AppSettings中配置 3 /// </summary> 4 /// <param name="key">key值</param> 5 /// <param name="value">相应值</param> 6 public static bool SetConfigValue(string key, string value) 7 { 8 try 9 { 10 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 11 if (config.AppSettings.Settings[key] != null) 12 config.AppSettings.Settings[key].Value = value; 13 else 14 config.AppSettings.Settings.Add(key, value); 15 config.Save(ConfigurationSaveMode.Modified); 16 ConfigurationManager.RefreshSection("appSettings"); 17 return true; 18 } 19 catch 20 { 21 return false; 22 } 23 }
获取AppSetting节点值1 /// <summary> 2 /// 获取AppSettings中某一节点值 3 /// </summary> 4 /// <param name="key"></param> 5 public static string GetConfigValue(string key) 6 { 7 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 8 if (config.AppSettings.Settings[key] != null) 9 return config.AppSettings.Settings[key].Value; 10 else 11 12 return string.Empty; 13 }