How to Read and Write IConfiguration in C
In modern .NET applications, IConfiguration serves as
the central interface for accessing application settings from various
sources such as appsettings.json, environment variables,
and command-line arguments. While IConfiguration is heavily
optimized for reading hierarchical data and mapping it to strongly typed
objects, modifying and persisting changes back to a configuration source
requires specific approaches. This guide demonstrates how to retrieve
configuration values using standard .NET patterns and how to update
settings both in-memory and persistently to disk.
Setting Up IConfiguration
In ASP.NET Core and modern .NET Worker services,
IConfiguration is registered in the dependency injection
(DI) container by default. For console applications, you can construct a
configuration instance manually using
ConfigurationBuilder:
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfiguration configuration = builder.Build();Reading Configuration Settings
There are three primary ways to read data from
IConfiguration:
1. Key Indexer and GetValue
You can read flat values or navigate hierarchy using a colon
(:) as a delimiter:
// Direct indexer access (returns string)
string appName = configuration["ApplicationName"];
string dbConnection = configuration["ConnectionStrings:DefaultConnection"];
// Strongly typed extraction using GetValue<T>
int timeoutSeconds = configuration.GetValue<int>("Settings:TimeoutSeconds", defaultValue: 30);2. Binding to Objects
For complex sections, bind a subsection to a Plain Old CLR Object (POCO):
public class AppSettings
{
public string Theme { get; set; } = "Light";
public int MaxRetries { get; set; }
}
// Option A: Using Get<T>()
var settings = configuration.GetSection("Settings").Get<AppSettings>();
// Option B: Using Bind() on an existing instance
var existingSettings = new AppSettings();
configuration.GetSection("Settings").Bind(existingSettings);3. The Options Pattern (Recommended in ASP.NET Core)
Register configurations during service setup to inject them via
IOptions<T>, IOptionsSnapshot<T>,
or IOptionsMonitor<T>:
// Program.cs
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("Settings"));
// Injected Service
public class ReportService
{
private readonly AppSettings _settings;
public ReportService(IOptionsSnapshot<AppSettings> options)
{
_settings = options.Value;
}
}Writing Configuration Settings
IConfiguration is primarily an in-memory, read-only
representation of merged configuration providers. However, updates can
be handled depending on whether you need them temporarily in memory or
persisted to storage.
1. In-Memory Updates
You can update a configuration key directly in memory. This affects the current application process:
configuration["Settings:Theme"] = "Dark";Note: Changes made this way are not automatically written back to
appsettings.json and will reset when the application
restarts.
2.
Persisting Configuration Changes to appsettings.json
To permanently update configuration, modify the underlying JSON file
directly using System.Text.Json.Nodes:
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
public static class ConfigurationWriter
{
public static void UpdateSetting(string filePath, string sectionName, string key, string value)
{
string json = File.ReadAllText(filePath);
JsonNode jsonNode = JsonNode.Parse(json);
if (jsonNode == null) return;
// Ensure the section exists
if (jsonNode[sectionName] == null)
{
jsonNode[sectionName] = new JsonObject();
}
// Update the value
jsonNode[sectionName][key] = value;
var options = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText(filePath, jsonNode.ToJsonString(options));
}
}Usage:
string appSettingsPath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
ConfigurationWriter.UpdateSetting(appSettingsPath, "Settings", "Theme", "Dark");When using reloadOnChange: true in your configuration
setup, saving the JSON file will automatically trigger
IConfiguration and IOptionsSnapshot<T> /
IOptionsMonitor<T> to reflect the new values without
restarting the application.