关于app.config不能即时保存读取的解决方案

1
2
3
4
5
6
7
8
public void saveValue(string Name, string Value)
{
    ConfigurationManager.AppSettings.Set(Name, Value);
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings[Name].Value = Value;
    config.Save(ConfigurationSaveMode.Modified);
    config = null;
}

用上面的函数总是等到程序运行结束,才将数据保存进去。

所以我们换了一种方式,以xml的方式进行保存及读取。直接上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static void SetAppConfig(string appKey, string appValue)
{
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
 
    var xNode = xDoc.SelectSingleNode("//appSettings");
 
    var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
    if (xElem != null) xElem.SetAttribute("value", appValue);
    else
    {
        var xNewElem = xDoc.CreateElement("add");
        xNewElem.SetAttribute("key", appKey);
        xNewElem.SetAttribute("value", appValue);
        xNode.AppendChild(xNewElem);
    }
    xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
 
public static string GetAppConfig(string appKey)
{
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
 
    var xNode = xDoc.SelectSingleNode("//appSettings");
 
    var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
 
    if (xElem != null)
    {
        return xElem.Attributes["value"].Value;
    }
    return string.Empty;
}

使用方式

设置

SetAppConfig("SourceDBIP", txtSourceAddress.Text.Trim());

读取

Setting.GetAppConfig("SourceDBIP")

posted @   Sandglass  阅读(6083)  评论(2编辑  收藏  举报
编辑推荐:
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 如何基于DeepSeek开展AI项目
历史上的今天:
2010-03-04 程序员式的幽默(灌水)
点击右上角即可分享
微信分享提示