You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Configuration;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Txgy.EWS.Client.Common.Helpers
|
|
{
|
|
public static class ConfigManager
|
|
{
|
|
private static Configuration _config;
|
|
private static string _configPath;
|
|
// 初始化配置对象
|
|
static ConfigManager()
|
|
{
|
|
_configPath = Assembly.GetExecutingAssembly().Location + ".config";
|
|
_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
|
|
}
|
|
// 获取设置值
|
|
public static string GetAppSetting(string key)
|
|
{
|
|
return ConfigurationManager.AppSettings[key];
|
|
}
|
|
// 更新设置值(重要)
|
|
public static void UpdateAppSetting(string key, string value)
|
|
{
|
|
try
|
|
{
|
|
// 1. 更新内存中的配置文件对象
|
|
if (_config.AppSettings.Settings[key] == null)
|
|
{
|
|
_config.AppSettings.Settings.Add(key, value);
|
|
}
|
|
else
|
|
{
|
|
_config.AppSettings.Settings[key].Value = value;
|
|
}
|
|
|
|
// 2. 保存到物理文件
|
|
_config.Save(ConfigurationSaveMode.Modified);
|
|
|
|
// 3. 强制刷新内存中的配置(否则需重启才能生效)
|
|
ConfigurationManager.RefreshSection("appSettings");
|
|
|
|
// 4. 更新当前内存中的ConfigurationManager
|
|
typeof(ConfigurationManager)
|
|
.GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static)
|
|
?.SetValue(null, 0);
|
|
|
|
typeof(ConfigurationManager)
|
|
.GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static)
|
|
?.SetValue(null, null);
|
|
}
|
|
catch (ConfigurationErrorsException ex)
|
|
{
|
|
// 处理配置文件错误
|
|
throw new ApplicationException("配置文件写入失败", ex);
|
|
}
|
|
}
|
|
}
|
|
}
|