Winform後台如何動態修改App.config文件里的內容

以下方法修改的,自己添加的app.config裡面不會顯示出修改的東西。

方法一:通過使用System.Xml.XmlDocument對象的方法進行bindebug~.vshost.exe.Config裡面的配置修改。(這種方法在程式下次啟動時才會生效,直到你清除項目重建 或是重新手動修改才會恢復為你自己寫的配置信息)

  public static void SetValue(string AppKey, string AppValue)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
            else
            {

              //如果沒有這個節點則添加
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
        }

方法二:使用Configuration對象進行修改。(這種方法即刻生效,但下次啟動時不生效)

 Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  conf.AppSettings.Settings["FilePath"].Value = fbd.SelectedPath(設置的新值);  
  conf.Save(ConfigurationSaveMode.Modified);
 ConfigurationManager.RefreshSection("appSettings");

多一分冷靜,少一分浮躁
原文地址:https://www.cnblogs.com/AnnyGird-LiMing/p/4860567.html