1. 程式人生 > >自定義xml配置檔案讀取更新

自定義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);
        }   

      
    }
}