How to Programmatically Update appsettings.json in C#
By FoxLearn 3/6/2025 3:45:10 AM 5
Below are the steps to follow:
- Load the
settings.json
and deserialize it into an object. - Modify the properties of the object.
- Serialize the object back into a JSON string and overwrite the
settings.json
file with the updated content.
There are two approaches you can use for deserialization:
- Deserialize the
settings.json
into a dynamic object. - Load
settings.json
with aConfigurationBuilder
into a strongly typed configuration class.
In this article, we'll explore both methods for updating existing properties and also demonstrate how to add a new property programmatically using the dynamic object approach.
For illustration, our initial settings.json
contains the following configuration:
{ "VolumeLevel": 50, "GraphicsSettings": { "Resolution": "1920x1080", "Fullscreen": true, "TextureQuality": "High" }, "Difficulty": "Medium" }
Deserialize settings.json
into a Dynamic Object
This method deserializes settings.json
into a dynamic object using Newtonsoft.Json
. After that, values can be modified directly, and the updated content is saved back into settings.json
.
We prefer using Newtonsoft.Json
here since it provides better support for dynamic objects compared to the built-in System.Text.Json
.
Step 1: Install Newtonsoft
If you don't have Newtonsoft.Json
installed, you can add it via NuGet:
Install-Package Newtonsoft.Json
Step 2: Load settings.json
and Deserialize It
First, read the content of settings.json
:
var settingsPath = Path.Combine(Directory.GetCurrentDirectory(), "settings.json"); var json = File.ReadAllText(settingsPath);
Now, deserialize it into a dynamic object using Newtonsoft.Json
:
var settings = JsonConvert.DeserializeObject<ExpandoObject>(json, new JsonSerializerSettings { Converters = { new ExpandoObjectConverter(), new StringEnumConverter() } });
Step 3: Modify Values
You can modify the properties like this:
settings.VolumeLevel = 75; settings.GraphicsSettings.TextureQuality = "Ultra"; settings.Difficulty = "Hard";
Step 4: Serialize and Overwrite settings.json
Finally, serialize the updated dynamic object and write it back to settings.json
:
var updatedJson = JsonConvert.SerializeObject(settings, Formatting.Indented); File.WriteAllText(settingsPath, updatedJson);
Using ConfigurationBuilder
to Load settings.json
into a Config Class
Alternatively, you can use ConfigurationBuilder
to load settings.json
into a strongly typed configuration class. This method works well if you're dealing with a structured file and want to ensure type safety.
Step 1: Install Necessary Packages
Install the required packages for ConfigurationBuilder
:
Install-Package Microsoft.Extensions.Configuration.Json Install-Package Microsoft.Extensions.Configuration.Binder
Step 2: Define a Config Class
Define classes that match the structure of your settings.json
:
public class GameSettings { public int VolumeLevel { get; set; } public GraphicsSettings GraphicsSettings { get; set; } public string Difficulty { get; set; } } public class GraphicsSettings { public string Resolution { get; set; } public bool Fullscreen { get; set; } public string TextureQuality { get; set; } }
Step 3: Load settings.json
into the Config Object
Use ConfigurationBuilder
to load settings.json
into the GameSettings
object:
var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") .Build() .Get<GameSettings>();
Step 4: Modify Values
You can now modify the values:
config.VolumeLevel = 100; config.GraphicsSettings.TextureQuality = "Ultra"; config.Difficulty = "Easy";
Step 5: Serialize and Overwrite settings.json
Finally, serialize the updated object and save it back to settings.json
:
var jsonWriteOptions = new JsonSerializerOptions { WriteIndented = true }; var updatedJson = JsonSerializer.Serialize(config, jsonWriteOptions); File.WriteAllText(settingsPath, updatedJson);
Adding a New Property Programmatically
If you want to add a new property to the settings.json
file, the dynamic approach is more flexible.
For example, How to add a new LastSaved
property:
dynamic dynamicSettings = JsonConvert.DeserializeObject<ExpandoObject>(json, new JsonSerializerSettings { Converters = { new ExpandoObjectConverter(), new StringEnumConverter() } }); var expando = dynamicSettings as IDictionary<string, object>; expando.Add("LastSaved", DateTime.Now); var newJson = JsonConvert.SerializeObject(dynamicSettings, Formatting.Indented); File.WriteAllText(settingsPath, newJson);
After this, your settings.json
will include the new LastSaved
property:
{ "VolumeLevel": 75, "GraphicsSettings": { "Resolution": "1920x1080", "Fullscreen": true, "TextureQuality": "Ultra" }, "Difficulty": "Hard", "LastSaved": "2025-03-06T15:25:00" }
In this article, we've explored two different approaches for updating settings.json
programmatically:
- Dynamic Object Approach: Ideal for simple, flexible changes where the structure may vary.
- ConfigurationBuilder with Strongly Typed Classes: Best for structured, type-safe configuration files.
Both methods allow you to read, modify, and overwrite the JSON file easily, and the dynamic approach also lets you add new properties to the configuration file on the fly.
- How to Get Status Codes with HttpClient in C#
- How to use TimeZoneInfo in C#
- How to Get key with the max value in a dictionary in C#
- How to Get and send JSON with HttpClient in C#
- How to Deserialize JSON as a stream in C#
- How to use JsonNode in C#
- TimeZoneInfo with current UTC offset in C#
- How to Parser a CSV file in C#