AppSettings操作类

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Common
{
    /// <summary>
    /// AppSettings操作类,作者:Ward
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 获取配置值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Get(string key)
        {
            var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //打开配置文件
            return cfg.AppSettings.Settings[key]?.Value;
        }
        /// <summary>
        /// 添加或修改,有值作修改,无值做添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool Set(string key, string value)
        {
            try
            {
                var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //打开配置文件
                if (string.IsNullOrEmpty(cfg.AppSettings.Settings[key].Key))
                {
                    cfg.AppSettings.Settings.Add(key, value); //添加配置节
                }
                else
                {
                    cfg.AppSettings.Settings[key].Value = value; //修改配置节
                }
                cfg.Save(); //保存
                ConfigurationManager.RefreshSection("appSettings"); //更新缓存
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool Del(string key)
        {
            try
            {
                var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //打开配置文件
                cfg.AppSettings.Settings.Remove(key); //删除配置节
                cfg.Save(); //保存
                ConfigurationManager.RefreshSection("appSettings"); //更新缓存
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
    }
}

 

posted @ 2016-11-26 13:56  -Ward-  阅读(365)  评论(0编辑  收藏  举报