How to Update .Net Core Application Settings Programmatically

Have you ever need to store small amounts of application state data where using Entity Framework or the file system was overkill? Every .Net Core application has an appsettings.json file. Why not use it to store data?

The first thing we need to do is get the path of the file:

var filePath = Path.Combine(AppContext.BaseDirectory, “appSettings.json”);

Next, read the contents of the file into memory and deserialize the text:

string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

Now, modify the key/value pair:

var sectionPath = key.Split(":")[0];
if (!string.IsNullOrEmpty(sectionPath))
{
     var keyPath = key.Split(":")[1];
     jsonObj[sectionPath][keyPath] = value;
}
else
{
     jsonObj[sectionPath] = value; // if no sectionpath just set the value
}

Finally, serialize the json and write the file output:

string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);

Here’s the full code:

private static void UpdateAppSetting<T>(string key, T value)
{
    try
    {
        var filePath = Path.Combine(AppContext.BaseDirectory, "appSettings.json");
        string json = File.ReadAllText(filePath);
        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

        var sectionPath = key.Split(":")[0];

        if (!string.IsNullOrEmpty(sectionPath))
        {
            var keyPath = key.Split(":")[1];
            jsonObj[sectionPath][keyPath] = value;
        }
        else
        {
            jsonObj[sectionPath] = value; // if no sectionpath just set the value
        }

        string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

        File.WriteAllText(filePath, output);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

Usage:

UpdateAppSetting<string>("AppSettings:LastRunDateTime", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss"));

About the Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You may also like these