简体   繁体   English

在 appsettings.json 文件中更改值的简单快捷方式

[英]Simple and quick way to change values in appsettings.json file

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.我即将采用旧的 .NET 应用程序到 .NET Core 3.1 将以前的 App.config 的处理更改为新的 appsettings.json 文件时遇到问题。 I've found a quick solution how to read from appsettings.json but I also need to change the values in it.我找到了一个快速解决方案,如何从 appsettings.json 中读取,但我还需要更改其中的值。 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.json 文件:

{
  "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:这是我写入 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:由于我没有找到更简单的方法,因此我实现了以下 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM