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

本文介绍了一种在网站运行过程中更新配置文件而不引起重启的方法,通过自定义配置文件避免了因webconfig更改导致的session丢失和长时间重启问题,适用于需要动态调整配置且保持用户体验连续性的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明: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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左左在右边

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值