5

Following this example, I am trying to retrieve and save startup application values using the IConfiguration interface from Microsoft.Extensions.Configuration API. However, I do not find a way to change those values into the settings JSON file.

As an example, consider the following appSettings.json configuration file:

"Setting":
{
  "Startup":
   {
      "IsFirstStart": true
   }
}

A the associated class in charge of extraction:

public class AppHandler
{
#region fields

  // MS heper contains configuration parameters from JSON file
  private IConfiguration _appConfiguration = null;

  // MS config builder
  private IConfigurationBuilder _appBuilder = null;

  // Is it software first use
  private bool _isFirstStart;

#endregion fields

#region Constructor

private AppHandler()
{
  _appBuilder = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
     .AddJsonFile($"appsettings.dev.json", optional: true, reloadOnChange: true)
     .AddEnvironmentVariables();

  _appConfiguration = _appBuilder.Build();
}

#endregion Constructor

#region Methods

private AppInitialized()
{
  //  Session initialization has been performed & store back the information in 'appSettings.json' file
  _appConfiguration["IsFirstStart"] = Convert.ToString(_isFirstStart = false);

  /*
   * HOW TO SAVE BACK IsFirstStart change into Json file?
   */
}

#endregion Methods
}

Moreover, I've seen ApplicationSettings class contains Save() method. I might implement this class instead, but what's the difference and which one do you recommand for UWP / WPF applications?

fofolevrai
  • 95
  • 1
  • 6

1 Answers1

3

in this context _appConfiguration is just an object holding your configuration in memory. Possible solution, would be to bind your configuration to a POCO, make your update and then create a File stream to overwrite your json file.

   var appConfig = new AppConfig()
        {
            //your appsettings.json props here
        }
        _appConfiguration.Bind(appConfig);

        appConfig.IsFirstStart = "...";

        string json = JsonConvert.SerializeObject(appConfig);
        System.IO.File.WriteAllText("appsettings.json", json);
Dimitar
  • 68
  • 7