沙滩星空的博客沙滩星空的博客

C# 读写自定义的Config文件

  1. 使用VS自带添加功能
    鼠标右键点击资源管理器的本项目文件夹添加新建项,选择:应用程序配置文件,创建App.config
  2. 手动创建 App.config 文件

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
     <appSettings>
         <add key="ENV" value="prod" />
     </appSettings>
    </configuration>
using System.Configuration;
 
namespace Utils
{
    public class ConfigHelper
    {
        private string ConfigPath = string.Empty;
 
        /// <summary>
        /// 获取配置文件指定的Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetConfig(string key)
        {
            Configuration ConfigurationInstance = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
            {
                ExeConfigFilename = ConfigPath
            }, ConfigurationUserLevel.None);
 
            if (ConfigurationInstance.AppSettings.Settings[key] != null)
                return ConfigurationInstance.AppSettings.Settings[key].Value;
            else
                return string.Empty;
        }
 
        /// <summary>
        /// 设置配置文件指定的Key,如果Key不存在则添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="vls"></param>
        /// <returns></returns>
        public bool SetConfig(string key, string vls)
        {
            try
            {
                Configuration ConfigurationInstance = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
                {
                    ExeConfigFilename = ConfigPath
                }, ConfigurationUserLevel.None);
 
                if (ConfigurationInstance.AppSettings.Settings[key] != null)
                    ConfigurationInstance.AppSettings.Settings[key].Value = vls;
                else
                    ConfigurationInstance.AppSettings.Settings.Add(key, vls);
 
                ConfigurationInstance.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }
 
 
        public ConfigHelper(string configPath)
        {
            ConfigPath = configPath;
        }
    }
}

using System;
using Utils;

string configPath = Application.StartupPath + "\\App.config";
var conf = new ConfigHelper(configPath);
bool result = conf.SetConfig("ENV", "dev");
string value = ConfigHelpers.GetConfig("ENV");


C# 读写自定义的Config文件 https://blog.csdn.net/qq_38693757/article/details/125549559
使用 Visual C# 存储和检索应用程序配置文件中的自定义信息 https://docs.microsoft.com/zh-cn/troubleshoot/developer/visualstudio/csharp/language-compilers/store-custom-information-config-file
未经允许不得转载:沙滩星空的博客 » C# 读写自定义的Config文件

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址