在.Net Framework版本可以使用ConfigurationManager
通常是指app.config或web.config
命名空间
System.Configuration下的ConfigurationManagerprivate void UpdateConfig(string key,string value)
{Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);config.AppSettings.Settings[key].Value = value;config.Save(ConfigurationSaveMode.Full);//加载到内存中ConfigurationManager.RefreshSection("appSettings");
}
.Net Core之后ConfigurationManager不在标准命名空间内,可以使用IConfiguration
命名空间
using Microsoft.Extensions.Configuration;
public static class ConfigHelper
{private static IConfiguration _configuration;public static IConfiguration Configuration{get{_configuration ??= new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).Build();//optional标识该配置是否是必须的,reloadOnChange标识是否实时加载修改,用程序改的好像不太生效return _configuration;}}public static string? GetValue(string key){return Configuration[key];}public static void SetValue(string key, string value){Configuration[key] = value;}public static void SaveChanges(){var configPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");var jsonConfig = File.ReadAllText(configPath);var jObject = JsonConvert.DeserializeObject<JObject>(jsonConfig);if (jObject == null)return;foreach(var item in Configuration.AsEnumerable()){if (jObject.TryGetValue(item.Key, out _)){jObject[item.Key] = item.Value;}}File.WriteAllText(configPath, JsonConvert.SerializeObject(jObject));}
}