C#操作配置文件
读取指定节点的值:
1 ///<summary> 2 ///返回*.config文件中appSettings配置节的value项 3 ///</summary> 4 ///<param name="strKey"></param> 5 ///<returns></returns> 6 public static string GetAppConfig(string strKey) 7 { 8 foreach (string key in ConfigurationManager.AppSettings) 9 { 10 if (key == strKey) 11 { 12 return ConfigurationManager.AppSettings[strKey]; 13 } 14 } 15 return null; 16 }
修改以及增加一个节点(Key),修改其实就是判断该Key是否存在,存在则删除,再创建。
1 ///<summary> 2 ///在*.config文件中appSettings配置节增加一对键、值对 3 ///</summary> 4 ///<param name="newKey"></param> 5 ///<param name="newValue"></param> 6 public static void UpdateAppConfig(string newKey, string newValue) 7 { 8 bool isModified = false; 9 foreach (string key in ConfigurationManager.AppSettings) 10 { 11 if (key == newKey) 12 { 13 isModified = true; 14 } 15 } 16 17 18 Configuration config = 19 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 20 // 如果操作的Key 已存在,则删除 21 if (isModified) 22 { 23 config.AppSettings.Settings.Remove(newKey); 24 } 25 // 在配置文件中添加节点 26 config.AppSettings.Settings.Add(newKey, newValue); 27 // 修改配置文件后还需要保存 28 config.Save(ConfigurationSaveMode.Modified); 29 // 重置配置文件,如果不执行这行语句,已更新的配置文件不会得到应用 30 ConfigurationManager.RefreshSection("appSettings"); 31 }
读写配置文件很简单,也很方便。