自定義處理app.config/web.config類

 

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

namespace CS
{
    ///   <summary>  
    ///   應用程序配置文件
    ///   </summary>  
    public class AppConfig
    {
        private bool updated = false;
        private XmlDocument cfg;
        private AppDomain app;

        /// <summary>
        /// 初始化當前應用程序配置
        /// </summary>
        public AppConfig()
        {
            cfg = new XmlDocument();
            app = AppDomain.CurrentDomain;

            this.Load();
        }

        /// <summary>
        /// 加載配置文件
        /// </summary>
        public void Load()
        {
            this.updated = false;
            cfg.Load(app.SetupInformation.ConfigurationFile);
        }

        /// <summary>
        /// 獲取或設置節點值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string this[string key]
        {
            get
            {
                return GetAppValue(key);
            }

            set
            {
                SetAppValue(key, value);
            }
        }

        /// <summary>
        /// 設置一個節點的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="newValue"></param>
        public void SetAppValue(string key, string newValue)
        {
            cfg.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value = newValue;
            this.updated = true;
        }

        /// <summary>
        /// 保存修改到配置文件
        /// </summary>
        public void Save()
        {
            if (this.updated)
            {
                cfg.Save(app.SetupInformation.ConfigurationFile);
                this.updated = false;
            }
        }

        /// <summary>
        /// 保存修改到配置文件,並重新加載新配置
        /// </summary>
        public void Update()
        {
            this.Save();
            this.Load();
        }

        /// <summary>
        /// 獲取一個節點的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetAppValue(string key)
        {
            return cfg.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章