[英]Simple and quick way to change values in appsettings.json file
我即将采用旧的 .NET 应用程序到 .NET Core 3.1 将以前的 App.config 的处理更改为新的 appsettings.json 文件时遇到问题。 我找到了一个快速解决方案,如何从 appsettings.json 中读取,但我还需要更改其中的值。 互联网上充满了无用的东西。 我需要一个简单的解决方案来了解基础知识是如何工作的。
那是我的 appsettings.json 文件:
{
"AppSettings": {
"Server": "127.0.0.1",
"Music": 5,
"Sound": 5
}
}
这就是我从中阅读的方式:
internal static Settings LoadSettings()
{
// Default Settings
Settings settings = new Settings();
var config = new ConfigurationBuilder()
.SetBasePath(System.AppContext.BaseDirectory)
.AddJsonFile("appsettings.json",
optional: true,
reloadOnChange: true).Build();
// Load settings for music volume
if (int.TryParse(config["AppSettings:Music"], out int music))
settings.MusicVolume = music;
// Load settings for sound volume
if (int.TryParse(config["AppSettings:Sound"], out int sound))
settings.SoundVolume = sound;
// Load Server IP
string server = config["AppSettings:Server"];
if (!string.IsNullOrEmpty(server))
settings.Server = server;
return settings;
}
我应该如何以相同的方式写入/更新值? 没找到有用的...
这是我写入 App.config 的旧代码:
internal static void SaveSettings(Settings settings)
{
var conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
conf.AppSettings.Settings["Music"].Value = settings.MusicVolume.ToString();
conf.AppSettings.Settings["Sound"].Value = settings.SoundVolume.ToString();
conf.AppSettings.Settings["Server"].Value = settings.Server;
conf.Save(ConfigurationSaveMode.Modified);
}
由于我没有找到更简单的方法,因此我实现了以下 class ,它使用递归并将所有值写入 appsettings.json 文件中的正确位置:
private static class SettingsWriter
{
internal static void AddOrUpdateAppSetting<T>(string sectionPathKey, T value)
{
try
{
var filePath = Path.Combine(System.AppContext.BaseDirectory, "appsettings.json");
string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
SetValueRecursively(sectionPathKey, jsonObj, value);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);
}
catch (Exception ex)
{
Console.WriteLine("Error writing app settings | {0}", ex.Message);
}
}
private static void SetValueRecursively<T>(string sectionPathKey, dynamic jsonObj, T value)
{
// split the string at the first ':' character
var remainingSections = sectionPathKey.Split(":", 2);
var currentSection = remainingSections[0];
if (remainingSections.Length > 1)
{
// continue with the procress, moving down the tree
var nextSection = remainingSections[1];
SetValueRecursively(nextSection, jsonObj[currentSection], value);
}
else
{
// we've got to the end of the tree, set the value
jsonObj[currentSection] = value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.