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

xiaoxiao2025-10-12  7

说明: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);         }               } }

备注 在根目录新建config文件夹,并新建app.config文件

app.config内容示例

<?xml version="1.0" encoding="utf-8"?> <appSettings> <add key="TaskStartDate" value="2018-10-31" /> <add key="TaskTime" value="0" /> <add key="IncomeCount" value="10" /> </appSettings>

 

转载请注明原文地址: https://www.6miu.com/read-5037817.html

最新回复(0)