I'm about to adopt an old .NET app to .NET Core 3.1 Have a problem to change the handling of former App.config to the new appsettings.json file. I've found a quick solution how to read from appsettings.json but I also need to change the values in it. The internet is full of useless stuff. I need a simple solution for understanding how the basics are working.
That is my appsettings.json file:
{
"AppSettings": {
"Server": "127.0.0.1",
"Music": 5,
"Sound": 5
}
}
And that's how I read from it:
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;
}
How should I write/update the values in same manner? Couldn't find anything useful...
That is my old code for writing into 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);
}
Since I didn't find a simpler method, I have implemented the following class which uses recursion and writes all values to the right places in the appsettings.json file:
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.