1. 程式人生 > >winform 寫App.config配置文件——IT輪子系列(八)

winform 寫App.config配置文件——IT輪子系列(八)

項目 ble .exe private conf 遇到 配置信息 操作 src

前言

在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 else 11 { 12 //添加節點 13 config.AppSettings.Settings.Add(key, value); 14 } 15 config.Save(ConfigurationSaveMode.Modified);
16 ConfigurationManager.RefreshSection("appSettings"); 17 }

效果 如下:

技術分享圖片

好了,又搞到一個輪子,希望可以幫到大家。晚安....

winform 寫App.config配置文件——IT輪子系列(八)