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

前言

在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         }

效果 如下:

 

好了,又搞到一个轮子,希望可以帮到大家。晚安....

原文地址:https://www.cnblogs.com/liangxiarong/p/8034818.html