C#中动态读写App.config配置文件

时间:2021-01-21 17:19:27

转自:http://blog.csdn.net/taoyinzhou/article/details/1906996

app.config 修改后,如果使用cofnigurationManager立即读取,不能获取修改后的值,只能获取缓存中的原值。使用下面直接操场xml文件的方式可以动态读写配置文件。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;

namespace TaoNet.Common.TaoCommon
{
    /// <summary>
    /// C#中动态读写App.config配置文件
    /// </summary>
    public class AppConfig
    {
        public AppConfig()
        {
            ///
            /// TODO: 在此处添加构造函数逻辑
            ///
        }
        /// <summary>
        /// 写操作
        /// </summary>
        /// <param name="strExecutablePath"></param>
        /// <param name="AppKey"></param>
        /// <param name="AppValue"></param>
        public static void ConfigSetValue(string strExecutablePath,string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //获取可执行文件的路径和名称
            xDoc.Load(strExecutablePath + ".config");

            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//connectionStrings");
            // xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@name='" + AppKey + "']");
            if (xElem1 != null) xElem1.SetAttribute("connectionString", AppValue);
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("name", AppKey);
                xElem2.SetAttribute("connectionString", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(strExecutablePath + ".config");
        }

        /// <summary>
        /// 读操作
        /// </summary>
        /// <param name="strExecutablePath"></param>
        /// <param name="appKey"></param>
        /// <returns></returns>
        public string ConfigGetValue(string strExecutablePath, string appKey)
        {
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(strExecutablePath + ".config");

                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
                if (xElem != null)
                    return xElem.GetAttribute("value");
                else
                    return "";
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}