首页 > 编程语言 >C#配置文件读写(App.config)

C#配置文件读写(App.config)

时间:2023-10-18 16:38:22浏览次数:39  
标签:return string 配置文件 settings C# ConnectionStrings key configuration config

 

 

/*************************************************
 * 描述:
 * 
 * Author:ys
 * Date:2023/10/18 16:14:32
 * Update:
 * ************************************************/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo.Helper
{
    /// <summary>
    /// 针对配置文件的读写操作 (App.config)
    /// ps:key和name都不区分大小写
    /// </summary>
    public class AppConfigHelper
    {
        Configuration _configuration;

        /// <summary>
        /// 打开当前的config
        /// </summary>
        public AppConfigHelper()
        {
            _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        }

        /// <summary>
        /// 打开指定路径的config
        /// </summary>
        /// <param name="path"></param>
        public AppConfigHelper(string path)
        {
            _configuration = ConfigurationManager.OpenExeConfiguration(path);
        }

        /// <summary>
        /// 读取所有的AppSettings
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> ReadAllSettings()
        {
            Dictionary<string, string> dictKV = new Dictionary<string, string>();
            var settings = _configuration.AppSettings.Settings;
            foreach (string key in settings.AllKeys)
            {
                dictKV[key] = settings[key].Value;
            }
            return dictKV;
        }

        /// <summary>
        /// 读取AppSettings指定Key的Value
        /// </summary>
        /// <param name="key"></param>
        public string ReadSetting(string key)
        {
            var settings = _configuration.AppSettings.Settings;
            return settings[key].Value;
        }

        /// <summary>
        /// 修改AppSettings指定Key的值(没有就添加)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public bool AddUpdateSettings(string key, string value, bool noToAdd = true)
        {
            var settings = _configuration.AppSettings.Settings;
            if (settings[key] == null)
            {
                if (noToAdd)  //没有就添加
                {
                    settings.Add(key, value);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                settings[key].Value = value;
            }
            _configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(_configuration.AppSettings.SectionInformation.Name);
            return true;
        }

        /// <summary>
        /// 移除AppSettings指定Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool RemoveSetting(string key)
        {
            var settings = _configuration.AppSettings.Settings;
            if (settings[key] == null)
            {
                return false;
            }
            settings.Remove(key);
            _configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(_configuration.AppSettings.SectionInformation.Name);
            return true;
        }

        /// <summary>
        /// 读取所有的ConnectionStrings
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> ReadConnectionStrings()
        {
            Dictionary<string, string> dictKV = new Dictionary<string, string>();
            var connectionStrings = _configuration.ConnectionStrings.ConnectionStrings;
            foreach (ConnectionStringSettings key in connectionStrings)
            {
                dictKV[key.Name] = connectionStrings[key.Name].ConnectionString;
            }
            return dictKV;
        }

        /// <summary>
        /// 读取ConnectionStrings指定Name的ConnectionString
        /// </summary>
        /// <param name="name"></param>
        public string ReadConnectionString(string name)
        {
            var connectionStrings = _configuration.ConnectionStrings.ConnectionStrings;
            return connectionStrings[name].ConnectionString;
        }

        /// <summary>
        /// 修改ConnectionStrings指定Name的值(没有就添加)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="connectionString"></param>
        public bool AddUpdateConnectionString(string name, string connectionString, bool noToAdd = true)
        {
            var connectionStrings = _configuration.ConnectionStrings.ConnectionStrings;
            if (connectionStrings[name] == null)
            {
                if (noToAdd)  //没有就添加
                {
                    connectionStrings.Add(new ConnectionStringSettings(name, connectionString));
                }
                else
                {
                    return false;
                }
            }
            else
            {
                connectionStrings[name].ConnectionString = connectionString;
            }
            _configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(_configuration.ConnectionStrings.SectionInformation.Name);
            return true;
        }

        /// <summary>
        /// 移除ConnectionStrings指定Name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool RemoveConnectionString(string name)
        {
            var connectionStrings = _configuration.ConnectionStrings.ConnectionStrings;
            if (connectionStrings[name] == null)
            {
                return false;
            }
            connectionStrings.Remove(name);
            _configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(_configuration.ConnectionStrings.SectionInformation.Name);
            return true;
        }



    }
}

 

标签:return,string,配置文件,settings,C#,ConnectionStrings,key,configuration,config
From: https://www.cnblogs.com/yuanshuo/p/17772669.html

相关文章

  • c# Queue 队列的基本使用
    C#中的 Queue 是一种基于链表的先进先出(FIFO)数据结构。以下是一个简单的 Queue 实例:///<summary>///普通队列///</summary>publicvoidQueueShow(){//创建一个QueueQueue<string>queue=newQu......
  • WinSCP 脚本实现将 jar 包一键上传 Ubuntu 并 docker 部署
    准备首先,在Ubuntu写一个.sh脚本用于自动更新jar包的docker容器和镜像,然后在Windows写一个.bat脚本用于上传jar包并运行.sh脚本。deploy.sh#Kill容器dockerkilldemo#删除容器dockerrmdemo#删除镜像dockerrmimy/demo#构建镜像dockerbuild-t......
  • CSS-04
    定位将盒子定在一固定位置组成定位模式+边偏移定位模式static-静态定位(标准流)(相当于无定位)relative-相对absolute-绝对(脱标)fixed-固定(脱标)相对定位相对位置position:relative;​top:100px;相对自己的位置移动,原位置保留绝对定位相对祖先的位置移动没有......
  • Go - Creating Subtests to Have Finer Control Over Groups of Test Cases
    Problem: Youwanttocreatesubtestswithinatestfunctiontohavefinercontrolovertestcases.Solution: Usethet.Runfunctiontocreatesubtestswithinatestfunction.Subtestsextendtheflexibilityoftestfunctionstoanotherleveldown. When......
  • RX66T优化用于电机控制R5F566TFFGFP、R5F566TKGGFP、R5F566TKCGFP搭载第三代RXv3 CPU
    1、RX66T 框图2、描述RX66T32位MCU是基于第三代RXv3CPU内核的旗舰32位RXMCU系列中的首款产品。这些MCU优化用于电机控制,可满足实时性能和增强稳定性要求。这些特性帮助实现下一代智能工厂设备和智能家电中的逆变器控制。这些MCU还具有下一代设计中嵌入式AI所需的额外处理能......
  • 【JAVA】cron定时怎么记 ss mi hh DD MM 星期 YY
      ......
  • c的基本语法
    逻辑运算&&和||的短路应当注意到,这两个运算符的两端会优先计算左端,如果左端结果将使结果确定,那么就不执行右端语句。&&和||的计算优先度&&的计算优先度更高,但二者的计算优先度均低于&和|。但如果||和&&同时存在,且||的一端为&&运算结果,当出现||的另一端结果为1,将不执行&&两端......
  • pytorch 量化相关参考
    ref:https://blog.csdn.net/znsoft/article/details/130788437importtorchimporttorch.quantizationclassM(torch.nn.Module):def__init__(self):super(M,self).__init__()self.quant=torch.quantization.QuantStub()#静态量化时量化桩......
  • kubeadm init 报错ERROR FileContent--proc-sys-net-bridge-bridge-nf-call-iptables
    现象:[ERRORFileContent--proc-sys-net-bridge-bridge-nf-call-iptables]:/proc/sys/net/bridge/bridge-nf-call-iptablescontentsarenotsetto1原因:  /proc/sys/net/bridge/bridge-nf-call-iptables 文件的内容并没有设置为1解决方案echo"1">/proc/sys/net/br......
  • mysql 运行没错,在mybatis中报错 druid 报错 syntax error, expect RPAREN, actual
    您遇到的问题可能是由于Druid版本较旧导致的。在Druid 1.0.19中,对于某些语法结构的处理存在一些限制和问题。针对您的具体情况,可以尝试以下解决方案:1. 确保SQL语句的括号匹配正确。错误消息"expect RPAREN, actual IDENTIFIER DAY"表明Druid期望一个右括号(RPAREN),但实际上......