How to write data to appsettings.json in a console application (.net Core)?

Viewed 3654

To read data from appsettings.json I useConfigurationBuilder, ConfigurationBinder.
   ConfigurationBuilder,ConfigurationBinder allow you to read data from appsettings.json.

Questions:
- How to write data to appsettings.json in a console application?
Can I write data to appsettings.json usingConfigurationBuilder, ConfigurationBinder?
Or do I need to use JsonConvert.DeserializeObject <Settings> (fileText) to write data to appsettings.json?
In other words, if you use JsonConvert.DeserializeObject, then I should:
- read the data appsettings.json;
- change the data in the desired section;
- save the data in appsettings.json.

 Do I understand the logic of working with appsettings.json?

Picture-1
enter image description here

Picture-2
enter image description here

Code AppSettings.cs

namespace ConsoleAppCore
{
    class AppSettings
    {
        public string KeyA_SecMain { get; set; }
        public string KeyB_SecMain { get; set; }        
    }
}

Code appsettings.json

   {
  "SectionMain": {
    "KeyA_SecMain": "KeyA_SecMain_Value",
    "KeyB_SecMain": "KeyB_SecMain_Value"
  }
}

Code ReadWriteAppSettings.cs

using Microsoft.Extensions.Configuration;           
using System.IO;                                    

namespace ConsoleAppCore
{
    class ReadWriteAppSettings
    {
        /// <summary>
        /// Read GetSection AppSettings
        /// </summary>
        /// <returns></returns>
        public string ReadGetSectionAppSettings()
        {
            var builder = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();

            string result = configuration.GetSection("SectionMain:KeyA_SecMain").Value;

            return result;
        }


        /// <summary>
        /// Bind AppSettings
        /// </summary>
        /// <returns></returns>
        public void BindAppSettings()
        {
            AppSettings appSettings = new AppSettings();

            var builder = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            var configuration = builder.Build();

            var configurationResult = configuration.GetSection("SectionMain");

            ConfigurationBinder.Bind(configurationResult, appSettings);

            string result_KeyA_Sec1 = appSettings.KeyA_SecMain;
            string result_KeyB_Sec1 = appSettings.KeyB_SecMain;            
        }        
    }
}

Code Program.cs

namespace ConsoleAppCore
{
    class Program
    {
        static void Main(string[] args)
        {            
            ReadGetSectionAppSettings();
            BindAppSettings();            
        }        

        static public string ReadGetSectionAppSettings()
        {
            ReadWriteAppSettings readWriteAppSettings = new ReadWriteAppSettings();
            string str = readWriteAppSettings.ReadGetSectionAppSettings();

            return str;
        }

        static public void BindAppSettings()
        {
            ReadWriteAppSettings readWriteAppSettings = new ReadWriteAppSettings();
            readWriteAppSettings.BindAppSettings();
        }

    }
}
1 Answers

I use this helper class. Class writes setting to appsettings.json file in /bin folder. If you need another path just modify path to appsettings.json file.

public static class SettingsHelpers
{
    public static void AddOrUpdateAppSetting<T>(string sectionPathKey, T value)
    {
        try
        {
            var filePath = Path.Combine(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;
        }
    }
}

Using:

 SettingsHelpers.AddOrUpdateAppSetting<int>("Page", 5);
Related