zoukankan      html  css  js  c++  java
  • c# 修改winform中app.config的配置值

         public bool ChangeConfig(string AppKey,string AppValue)
            {
                bool result = true;
                try
                {
                    XmlDocument xDoc = new XmlDocument();
                    //获取App.config文件绝对路径
                    String basePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    basePath = basePath.Substring(0, basePath.Length - 10);
                    String path = basePath + "App.config";
                    xDoc.Load(path);
    
                    XmlNode xNode;
                    XmlElement xElem1;
                    XmlElement xElem2;
                    //修改完文件内容,还需要修改缓存里面的配置内容,使得刚修改完即可用
                    //如果不修改缓存,需要等到关闭程序,在启动,才可使用修改后的配置信息
                    Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    xNode = xDoc.SelectSingleNode("//appSettings");
                    xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
                    if (xElem1 != null)
                    {
                        xElem1.SetAttribute("value", AppValue);
                        cfa.AppSettings.Settings[AppKey].Value = AppValue;
                    }
                    else
                    {
                        xElem2 = xDoc.CreateElement("add");
                        xElem2.SetAttribute("key", AppKey);
                        xElem2.SetAttribute("value", AppValue);
                        xNode.AppendChild(xElem2);
                        cfa.AppSettings.Settings.Add(AppKey, AppValue);
                    }
                    //改变缓存中的配置文件信息(读取出来才会是最新的配置)
                    cfa.Save();
                    ConfigurationManager.RefreshSection("appSettings");
                    xDoc.Save(path);
                }
                catch (Exception ex)
                {
                    _log.Error("修改App.config文件出错:"+ex.Message);
                    result = false;
                }
                return result;
            }
  • 相关阅读:
    IO流-----写到输出流
    MyBatis中collection (一对一,一对多)
    POI导出Excel并下载
    篇二:MySQL存储过程
    篇三:访问JSON静态文件
    ajax同步处理(使得JS按顺序执行)
    篇二:JSON解析
    篇一:MySQL中case when then
    乱码问题
    解决spring配置中的bean类型的问题:BeanNotOfRequiredTypeException
  • 原文地址:https://www.cnblogs.com/25miao/p/7206984.html
Copyright © 2011-2022 走看看