c#的AppConfig的简单类库封装

功能:

  1.在非调试状态下可对AppConfig.exe.Config(exe文件路径下)文件的appsettings节点进行简单的增删改查。

  2.在只需要一些简单配置即在appsettings节下添加key和value情况下较为方便。

  3.只支持对字符串的写入和读取,即是说读出内容后和写入内容前要进行转换。

使用:

  添加Cfg.dll到输出目录下,添加对Cfg.dll的引用即可调用类中函数。

代码:

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

namespace Cfg
{
    public class AppConfig
    {
        private System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        public bool GetValue(string keyName,out string value)
        {
            try
            {
                value = ConfigurationManager.AppSettings[keyName].ToString();
                return true;
            }
            catch
            {
                value = null;
                return false;
            }
            
        }
        public bool SetValue(string keyName, string content)
        {
            try
            {
                config.AppSettings.Settings[keyName].Value = content;
                config.Save(ConfigurationSaveMode.Modified);
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool AddValue(string keyName, string value)
        {
            try
            {
                config.AppSettings.Settings.Add(keyName, value);
                config.Save(ConfigurationSaveMode.Modified);
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool DelleteValue(string keyName)
        {
            try
            {
                config.AppSettings.Settings.Remove(keyName);
                config.Save(ConfigurationSaveMode.Modified);
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/jiabin-zhang/p/10718138.html