自定义xml配置文件读取更新

说明:webconfig的文件中的值的更新会引起网站重启,网站重启内存挥手,session等信息会丢失,所以下面这些场景我们需要自定义配置文件。

         1,网站运行中,我们需要更新配置文件来关闭某些功能,不能造成用户cookie等信息丢失。

         2,网站加载了大量缓存,重启时间太长。

         3,webConfig配置了大量其他的配置,追加的话不好维护。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Xml;

namespace Loulan
{
    public class ConfigHelp
    {
       

        public static string GetAppConfig(string appKey)
        {
            XmlDocument document = new XmlDocument();
            string filename = HttpRuntime.AppDomainAppPath + @"config\app.config";
            document.Load(filename);
            XmlElement element = (XmlElement)document.SelectSingleNode("//appSettings").SelectSingleNode("//add[@key='" + appKey + "']");
            if (element != null)
            {
                return element.Attributes["value"].Value;
            }
            return string.Empty;
        }

       

        public static void AddOrUpdateAppConfig(string appKey, string appValue)
        {
            XmlDocument document = new XmlDocument();
            string filename = HttpRuntime.AppDomainAppPath + @"config\app.config";
            document.Load(filename);
            System.Xml.XmlNode node = document.SelectSingleNode("//appSettings");
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + appKey + "']");
            if (element != null)
            {
                element.SetAttribute("value", appValue);
            }
            else
            {
                XmlElement newChild = document.CreateElement("add");
                newChild.SetAttribute("key", appKey);
                newChild.SetAttribute("value", appValue);
                node.AppendChild(newChild);
            }
            document.Save(filename);
        }   

      
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41609327/article/details/83385777