[英]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.