6

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?

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for this belated acceptance. That's exactly the working solution I was looking for. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.