修改app.config,并保留注释的方法

    /// <summary>
        /// 新增或修改appSettings 保留注释
        /// </summary>
        /// <param name="configPath"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool Set(string configPath, string key, string value)
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(configPath);
                XmlNode node0 = xml.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']");
                if (node0 == null)
                {
                    var node = xml.CreateElement("add");
                    node.SetAttribute("key", key);
                    node.SetAttribute("value", value);
                    var parentNode = xml.SelectSingleNode("/configuration/appSettings");
                    parentNode.AppendChild(node);
                }
                else
                {
                    node0.Attributes["value"].Value = value;
                }
                xml.Save(configPath);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch (Exception e)
            {
                Logger.LogError("新增或修改appSettings", e);
            }
            return false;
        }

 

posted @ 2021-02-08 10:44  simadi  阅读(525)  评论(0编辑  收藏  举报