0

I am currently working on project using asp.net core v2.0, and in my appsettings.json I have:

"ContextSettings": {
    "ConnectionString": "Data Source={base-path}WahupaWeb.sqlite;Version=3;BinaryGUID=True;datetimeformat=CurrentCulture",
    "Provider": "System.Data.SQLite.EF6",
    "DropCreateDatabaseAlways": "false"
  }

I have a scenario where I need to update "data source" of connection string programmatically.

I am reading and trying to update JSON file using this code.

public class FileController : Controller
{
   private IConfigurationRoot Configuration { get; set; }    
   private void ConfigureConnectionString(string dbFileName)
   {
     var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                      .SetBasePath(Environment.CurrentDirectory)
                      .AddJsonFile("appsettings.json", false, reloadOnChange: true);
     Configuration = builder.Build();
     Configuration["ContextSettings:ConnectionString"] = sqliteConnectionString;
   }
}

But it is not updating the file name "appsettings.json".

How to update appsettings.json file programmatically.

Hamid
  • 1
  • 1
  • 1
  • Possible duplicate of [How to update values into appsetting.json?](https://stackoverflow.com/questions/40970944/how-to-update-values-into-appsetting-json) – Kevin LaBranche Apr 03 '18 at 14:36
  • Nothing built in but you can do this yourself. See https://stackoverflow.com/questions/40970944/how-to-update-values-into-appsetting-json for an example. :-) – Kevin LaBranche Apr 03 '18 at 14:36

1 Answers1

4

Configuration is technically read-only. In other words, you can't just change something on the Configuration object and have it write those changes to disk. It's not set up that way.

If you need to programmatically change something like appsettings.json, you'd need to manually read the file, make your modifications and write those back to disk. The same as you would for any file. Since it's JSON, you'd likely want to use an intermediary like JSON.NET to actually deserialize the JSON in the file, alter the object in memory, and then serialize it again, before writing to the file.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444