標籤:xml檔案 包含 winform 讀寫 settings manager 方法 pat sys
前言
在winform項目中,常常需要讀app.config檔案。如:
1 var version = System.Configuration.ConfigurationManager.AppSettings["version"];
而“寫”,以前想當然是這樣的:
1 ConfigurationManager.AppSettings.Set("version","1.0.0");
可這樣寫並沒有成功,不懂什麼原因。那時就以為這個app.config是不允許寫操作的。對於配置資訊修改需求,只能通過讀寫xml檔案實現。不知,各位有沒有遇到過。
今天網上偶然找到一個可以寫app.config 的方法,代碼如下:
1 private void SetAppSettingsValue(string key, string value) 2 { 3 string file = System.Windows.Forms.Application.ExecutablePath; 4 Configuration config = ConfigurationManager.OpenExeConfiguration(file); 5 //判斷是否包含節點 6 if (config.AppSettings.Settings.AllKeys.Contains(key)) 7 { 8 config.AppSettings.Settings[key].Value = value; 9 }10 else11 {12 //添加節點13 config.AppSettings.Settings.Add(key, value);14 }15 config.Save(ConfigurationSaveMode.Modified);16 ConfigurationManager.RefreshSection("appSettings");17 }效果 如下:
好了,又搞到一個輪子,希望可以幫到大家。晚安....
winform 寫App.config設定檔——IT輪子系列(八)