zoukankan      html  css  js  c++  java
  • 关于app.config不能即时保存读取的解决方案

    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的方式进行保存及读取。直接上代码。

    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")

  • 相关阅读:
    CC初试啼声-----演讲与我
    static关键字修饰类
    maven可选依赖(Optional Dependencies)和依赖排除(Dependency Exclusions)
    Installation Directory must be on a local hard drive解决办法
    回顾JDBC
    java中的定时器
    怎么删除windows中无用的服务
    java实现简单的素数判断
    SQL注入
    @Override must override a superclass method 问题解决
  • 原文地址:https://www.cnblogs.com/homezzm/p/3580079.html
Copyright © 2011-2022 走看看