Configuration files

suggest change

Most programs need settings that shouldn't be hard-coded: database hosts, ports, timeouts, feature flags, log levels, user preferences. Putting them in a file lets you change behavior without recompiling, and have different values for development and production.

In modern .NET there are three common approaches:

Examples use C# 14 / .NET 10 and run as file-based programs (dotnet run app.cs). Packages are referenced with #:package. In a project, use dotnet add package instead.

appsettings.json with Microsoft.Extensions.Configuration

The examples below read this appsettings.json:

{
  // comments are allowed in appsettings.json
  "AppName": "Inventory",
  "MaxItems": 250,
  "Database": {
    "Host": "localhost",
    "Port": 5432,
    "Timeout": "00:00:30"
  },
  "AllowedHosts": [ "example.com", "api.example.com" ],
  "ConnectionStrings": {
    "Default": "Host=localhost;Database=inventory"
  }
}

The JSON is flattened into keys separated by :. Nested objects become Database:Host, and array elements are indexed: AllowedHosts:0, AllowedHosts:1. All values are stored as strings and converted when you ask for a typed value.

#:package Microsoft.Extensions.Configuration.Json@10.0.13
#:package Microsoft.Extensions.Configuration.Binder@10.0.13
using Microsoft.Extensions.Configuration;

IConfiguration config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false)
    .Build();

Console.WriteLine(config["AppName"]);
Console.WriteLine(config["Database:Host"]);
Console.WriteLine(config["AllowedHosts:1"]);
Console.WriteLine(config["Missing"] ?? "(null)");

int maxItems = config.GetValue<int>("MaxItems");
int port = config.GetValue<int>("Database:Port");
TimeSpan timeout = config.GetValue<TimeSpan>("Database:Timeout");
bool verbose = config.GetValue("Verbose", false);
Console.WriteLine($"{maxItems} {port} {timeout.TotalSeconds}s {verbose}");

Console.WriteLine(config.GetConnectionString("Default"));

IConfigurationSection db = config.GetSection("Database");
Console.WriteLine($"{db.Key} {db.Path} {db["Port"]}");
foreach (IConfigurationSection child in db.GetChildren())
    Console.WriteLine($"  {child.Key} = {child.Value}");

Console.WriteLine(config.GetSection("Nope").Exists());
Inventory
localhost
api.example.com
(null)
250 5432 30s False
Host=localhost;Database=inventory
Database Database 5432
  Host = localhost
  Port = 5432
  Timeout = 00:00:30
False

Things to know:

Where is the file looked up?

AddJsonFile resolves relative paths against the base path. Without SetBasePath, that's AppContext.BaseDirectory, the directory with the compiled program, not the current directory.

In a project, mark the file to be copied to the output directory so it's found both by dotnet run and after dotnet publish:

<ItemGroup>
  <None Update="appsettings*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

File-based apps (dotnet run app.cs) are compiled into a cache directory, so the examples here call SetBasePath(Directory.GetCurrentDirectory()) and read the file next to the script.

optional: false throws FileNotFoundException at Build() when the file is missing. Use optional: true for files that may not exist, like per-environment overrides.

Binding to classes

Reading keys one by one gets tedious. The binder maps a section onto an object, matching property names to keys (case-insensitively) and converting values:

#:package Microsoft.Extensions.Configuration.Json@10.0.13
#:package Microsoft.Extensions.Configuration.Binder@10.0.13
using Microsoft.Extensions.Configuration;

IConfiguration config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();

// whole tree into one object
AppSettings app = config.Get<AppSettings>()!;
Console.WriteLine($"{app.AppName} max={app.MaxItems}");
Console.WriteLine($"{app.Database.Host}:{app.Database.Port} timeout={app.Database.Timeout}");
Console.WriteLine(string.Join(", ", app.AllowedHosts));
Console.WriteLine(app.ConnectionStrings["Default"]);

// one section into a record with a primary constructor
DbSettings db = config.GetSection("Database").Get<DbSettings>()!;
Console.WriteLine(db);

// fill an existing instance (keeps values for keys that are missing)
var existing = new DatabaseOptions { Host = "x", MaxPoolSize = 50 };
config.GetSection("Database").Bind(existing);
Console.WriteLine($"{existing.Host} {existing.Port} pool={existing.MaxPoolSize}");

class AppSettings
{
    public string AppName { get; set; } = "";
    public int MaxItems { get; set; } = 100;
    public DatabaseOptions Database { get; set; } = new();
    public List<string> AllowedHosts { get; set; } = [];
    public Dictionary<string, string> ConnectionStrings { get; set; } = [];
}

class DatabaseOptions
{
    public string Host { get; set; } = "localhost";
    public int Port { get; set; } = 5432;
    public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15);
    public int MaxPoolSize { get; set; } = 20;
}

record DbSettings(string Host, int Port, TimeSpan Timeout);
Inventory max=250
localhost:5432 timeout=00:00:30
example.com, api.example.com
Host=localhost;Database=inventory
DbSettings { Host = localhost, Port = 5432, Timeout = 00:00:30 }
localhost 5432 pool=50

Catching mistakes

A value that can't be converted throws. But a misspelled key in the file is silently ignored by default, which is a common source of "my setting doesn't work" bugs. Turn on ErrorOnUnknownConfiguration to catch it:

#:package Microsoft.Extensions.Configuration.Binder@10.0.13
using Microsoft.Extensions.Configuration;

IConfiguration config = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string?>
    {
        ["Database:Host"] = "db.local",
        ["Database:Port"] = "not-a-number",
        ["Database:Hots"] = "typo",
    })
    .Build();

var opts = new DatabaseOptions { MaxPoolSize = 50 };
try
{
    config.GetSection("Database").Bind(opts);
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

try
{
    config.GetSection("Database").Get<DatabaseOptions>(o => o.ErrorOnUnknownConfiguration = true);
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

class DatabaseOptions
{
    public string Host { get; set; } = "localhost";
    public int Port { get; set; } = 5432;
    public int MaxPoolSize { get; set; } = 20;
}
Failed to convert configuration value 'not-a-number' at 'Database:Port' to type 'System.Int32'.
'ErrorOnUnknownConfiguration' was set on the provided BinderOptions, but the following properties were not found on the instance of DatabaseOptions: 'Hots'

AddInMemoryCollection is handy in tests and for built-in defaults: it's a configuration source like any other.

By default the binder uses reflection. In apps with PublishAot or trimming enabled (file-based apps have PublishAot on by default), the SDK turns on a source generator (EnableConfigurationBindingGenerator) that generates the binding code at compile time. Your code stays the same.

Layering: environments, environment variables, command line

The real power of the configuration system is combining sources. Each source is added in order, and a later source overrides earlier ones key by key. The usual order:

  1. appsettings.json: defaults, checked into source control
  2. appsettings.{Environment}.json: overrides for Development, Staging, Production
  3. environment variables: per-machine or per-container values, secrets
  4. command-line arguments: one-off overrides

Add an appsettings.Development.json:

{
  "Database": {
    "Host": "dev-db.local"
  },
  "Logging": {
    "Level": "Debug"
  }
}
#:package Microsoft.Extensions.Configuration.Json@10.0.13
#:package Microsoft.Extensions.Configuration.EnvironmentVariables@10.0.13
#:package Microsoft.Extensions.Configuration.CommandLine@10.0.13
using Microsoft.Extensions.Configuration;

string env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production";

IConfigurationRoot config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false)
    .AddJsonFile($"appsettings.{env}.json", optional: true)
    .AddEnvironmentVariables(prefix: "INVENTORY_")
    .AddCommandLine(args)
    .Build();

Console.WriteLine($"Environment:   {env}");
Console.WriteLine($"Database:Host: {config["Database:Host"]}");
Console.WriteLine($"Database:Port: {config["Database:Port"]}");
Console.WriteLine($"MaxItems:      {config["MaxItems"]}");
Console.WriteLine($"Logging:Level: {config["Logging:Level"] ?? "(not set)"}");

// which provider supplied each value?
Console.WriteLine(config.GetDebugView());

Running it with an environment, an environment variable and a command-line argument (bash syntax):

DOTNET_ENVIRONMENT=Development INVENTORY_Database__Port=6543 dotnet run app.cs -- --MaxItems 10
Environment:   Development
Database:Host: dev-db.local
Database:Port: 6543
MaxItems:      10
Logging:Level: Debug
AllowedHosts:
  0=example.com (JsonConfigurationProvider for 'appsettings.json' (Required))
  1=api.example.com (JsonConfigurationProvider for 'appsettings.json' (Required))
AppName=Inventory (JsonConfigurationProvider for 'appsettings.json' (Required))
ConnectionStrings:
  Default=Host=localhost;Database=inventory (JsonConfigurationProvider for 'appsettings.json' (Required))
Database:
  Host=dev-db.local (JsonConfigurationProvider for 'appsettings.Development.json' (Optional))
  Port=6543 (EnvironmentVariablesConfigurationProvider Prefix: 'INVENTORY_')
  Timeout=00:00:30 (JsonConfigurationProvider for 'appsettings.json' (Required))
Logging:
  Level=Debug (JsonConfigurationProvider for 'appsettings.Development.json' (Optional))
MaxItems=10 (CommandLineConfigurationProvider)

GetDebugView() is the quickest way to answer "where does this value come from?". Don't log it in production, because it prints secrets too.

Notes:

The options pattern with the Generic Host

In ASP.NET Core and Generic Host apps you don't build configuration yourself. Host.CreateApplicationBuilder (and WebApplication.CreateBuilder) already loads appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables (DOTNET_ prefixed and unprefixed) and the command line, in that order. The environment name comes from DOTNET_ENVIRONMENT and defaults to Production.

The recommended way to consume settings is the options pattern: bind a section to a class, register it in dependency injection and inject IOptions<T>. You also get validation:

#:package Microsoft.Extensions.Hosting@10.0.13
#:package Microsoft.Extensions.Options.DataAnnotations@10.0.13
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Logging.ClearProviders(); // keep the output short
// appsettings.json, appsettings.{Environment}.json, user secrets (Development),
// environment variables and command line are already added

builder.Services.AddOptions<DatabaseOptions>()
    .Bind(builder.Configuration.GetSection(DatabaseOptions.Section))
    .ValidateDataAnnotations()
    .Validate(o => !o.Host.Contains(' '), "Host must not contain spaces")
    .ValidateOnStart();

builder.Services.AddSingleton<Repository>();

using IHost host = builder.Build();
try
{
    await host.StartAsync(); // ValidateOnStart runs here
}
catch (OptionsValidationException e)
{
    foreach (string failure in e.Failures) Console.WriteLine($"config error: {failure}");
    return 1;
}

host.Services.GetRequiredService<Repository>().Connect();
await host.StopAsync();
return 0;

class DatabaseOptions
{
    public const string Section = "Database";

    [Required]
    public string Host { get; set; } = "";

    [Range(1, 65535)]
    public int Port { get; set; } = 5432;

    public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15);
}

class Repository(IOptions<DatabaseOptions> options)
{
    private readonly DatabaseOptions _db = options.Value;

    public void Connect() =>
        Console.WriteLine($"connecting to {_db.Host}:{_db.Port} (timeout {_db.Timeout.TotalSeconds}s)");
}
$ dotnet run app.cs
connecting to localhost:5432 (timeout 30s)

$ dotnet run app.cs -- --Database:Port 70000 --Database:Host "bad host"
config error: DataAnnotation validation failed for 'DatabaseOptions' members: 'Port' with the error: 'The field Port must be between 1 and 65535.'.
config error: Host must not contain spaces

Without ValidateOnStart, validation runs lazily the first time something reads options.Value, which may be minutes after startup or deep inside a request. Validate at startup so a bad config file stops the app right away with a clear message. Data Annotation lists the available validation attributes.

Repository depends on IOptions<DatabaseOptions>, not on IConfiguration. It doesn't know about key names or files, and in a unit test you can pass Options.Create(new DatabaseOptions { ... }).

Reloading when the file changes

With reloadOnChange: true the JSON provider watches the file and reloads it when it's saved. Subscribe to the reload token to react:

#:package Microsoft.Extensions.Configuration.Json@10.0.13
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;

string dir = Path.Combine(Path.GetTempPath(), "reload-demo");
Directory.CreateDirectory(dir);
string file = Path.Combine(dir, "settings.json");
File.WriteAllText(file, """{ "LogLevel": "Information" }""");

IConfigurationRoot config = new ConfigurationBuilder()
    .SetBasePath(dir)
    .AddJsonFile("settings.json", optional: false, reloadOnChange: true)
    .Build();

var changed = new TaskCompletionSource();
using IDisposable registration = ChangeToken.OnChange(
    () => config.GetReloadToken(),
    () =>
    {
        Console.WriteLine($"reloaded: LogLevel = {config["LogLevel"]}");
        changed.TrySetResult();
    });

Console.WriteLine($"start: LogLevel = {config["LogLevel"]}");
File.WriteAllText(file, """{ "LogLevel": "Debug" }""");

await changed.Task.WaitAsync(TimeSpan.FromSeconds(5));
Console.WriteLine($"now: LogLevel = {config["LogLevel"]}");
start: LogLevel = Information
reloaded: LogLevel = Debug
now: LogLevel = Debug

A reload token fires only once, which is why ChangeToken.OnChange takes a factory: it gets a fresh token after every change. Editors often save a file in several steps, so the callback can run more than once for one save. Keep it idempotent.

The host loads appsettings*.json with reloadOnChange: true. With options, the interface you inject decides whether you see new values:

Interface Lifetime Sees changes
IOptions<T> singleton, read once no
IOptionsSnapshot<T> scoped, re-read per scope (e.g. per HTTP request) yes, on next scope
IOptionsMonitor<T> singleton yes, CurrentValue and OnChange
#:package Microsoft.Extensions.Hosting@10.0.13
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Logging.ClearProviders();
builder.Services.Configure<DatabaseOptions>(builder.Configuration.GetSection("Database"));

using IHost host = builder.Build();
var monitor = host.Services.GetRequiredService<IOptionsMonitor<DatabaseOptions>>();
Console.WriteLine($"start: {monitor.CurrentValue.Host}");

var changed = new TaskCompletionSource();
using IDisposable? sub = monitor.OnChange(o =>
{
    Console.WriteLine($"changed: {o.Host}");
    changed.TrySetResult();
});

// simulate an admin editing the file while the app runs
string json = File.ReadAllText("appsettings.json");
File.WriteAllText("appsettings.json", json.Replace("\"localhost\"", "\"db2.local\""));

await changed.Task.WaitAsync(TimeSpan.FromSeconds(5));
Console.WriteLine($"now: {monitor.CurrentValue.Host}");

class DatabaseOptions
{
    public string Host { get; set; } = "";
    public int Port { get; set; }
}
start: localhost
changed: db2.local
now: db2.local

Reloading is good for things like log levels and feature flags. For settings like a connection string or a listening port, code usually reads the value once at startup, so a reload has no effect until restart.

XML, INI and other providers

JSON is the default, but the same API reads other formats. Each format is a separate package:

; settings.ini: sections become key prefixes
AppName=Inventory

[Database]
Host=ini-db.local
Port=5433
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <Database>
    <Host>xml-db.local</Host>
    <Port>5434</Port>
  </Database>
  <Feature name="Search" enabled="true" />
</configuration>
#:package Microsoft.Extensions.Configuration.Ini@10.0.13
#:package Microsoft.Extensions.Configuration.Xml@10.0.13
using Microsoft.Extensions.Configuration;

IConfiguration ini = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddIniFile("settings.ini")
    .Build();
Console.WriteLine($"{ini["AppName"]} {ini["Database:Host"]}:{ini["Database:Port"]}");

IConfiguration xml = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddXmlFile("settings.xml")
    .Build();
Console.WriteLine($"{xml["Database:Host"]}:{xml["Database:Port"]}");
Console.WriteLine($"{xml["Feature:Search:enabled"]}"); // name attribute becomes a key segment

// in-memory defaults, overridden by the INI file
IConfiguration mem = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string?>
    {
        ["Database:Host"] = "default-host",
        ["Database:Port"] = "5432",
    })
    .AddIniFile(Path.Combine(Directory.GetCurrentDirectory(), "settings.ini"))
    .Build();
Console.WriteLine($"{mem["Database:Host"]}:{mem["Database:Port"]}");
Inventory ini-db.local:5433
xml-db.local:5434
true
ini-db.local:5433

The root XML element name is ignored, and attributes are treated like child elements. Because every format ends up as the same flat key/value tree, you can mix them and bind the result to the same classes.

Other sources include AddUserSecrets (development secrets stored outside the project, managed with dotnet user-secrets set "Database:Password" "..."), AddKeyPerFile (one file per key, used for Docker and Kubernetes secrets) and third-party providers for Azure Key Vault, AWS Parameter Store and others. Never put real passwords in appsettings.json that's committed to source control.

Per-user settings with System.Text.Json

Microsoft.Extensions.Configuration is read-only. A desktop or CLI app that remembers user choices (theme, recent files, window position) needs to write settings back. The simplest solution is a plain class serialized with System.Text.Json to a file in the user's application data directory:

using System.Text.Json;
using System.Text.Json.Serialization;

string path = UserSettings.DefaultPath("MyNotes");
Console.WriteLine(path);

UserSettings s = UserSettings.Load(path);   // defaults on first run
Console.WriteLine($"theme={s.Theme} font={s.FontSize} recent={s.RecentFiles.Count}");

s.Theme = Theme.Dark;
s.RecentFiles.Insert(0, @"C:\notes\todo.md");
s.Save(path);

Console.WriteLine(File.ReadAllText(path));
UserSettings again = UserSettings.Load(path);
Console.WriteLine($"theme={again.Theme} recent={again.RecentFiles[0]}");

enum Theme { Light, Dark, System }

sealed class UserSettings
{
    public Theme Theme { get; set; } = Theme.System;
    public int FontSize { get; set; } = 14;
    public List<string> RecentFiles { get; set; } = [];
    public WindowPos? Window { get; set; }

    public static string DefaultPath(string appName) => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        appName, "settings.json");

    public static UserSettings Load(string path)
    {
        try
        {
            using FileStream fs = File.OpenRead(path);
            return JsonSerializer.Deserialize(fs, SettingsJson.Default.UserSettings) ?? new();
        }
        catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException)
        {
            return new UserSettings();
        }
    }

    public void Save(string path)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        // write to a temp file and swap, so a crash never leaves a half-written file
        string tmp = path + ".tmp";
        File.WriteAllText(tmp, JsonSerializer.Serialize(this, SettingsJson.Default.UserSettings));
        File.Move(tmp, path, overwrite: true);
    }
}

record WindowPos(int X, int Y, int Width, int Height);

// source-generated serializer: fast, trimming and AOT safe
[JsonSourceGenerationOptions(
    WriteIndented = true,
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
    ReadCommentHandling = JsonCommentHandling.Skip,  // allow // comments
    AllowTrailingCommas = true,                      // in hand-edited files
    UseStringEnumConverter = true,                   // "Dark", not 1
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(UserSettings))]
partial class SettingsJson : JsonSerializerContext;

Output on Windows:

C:\Users\kjk\AppData\Roaming\MyNotes\settings.json
theme=System font=14 recent=0
{
  "theme": "Dark",
  "fontSize": 14,
  "recentFiles": [
    "C:\\notes\\todo.md"
  ]
}
theme=Dark recent=C:\notes\todo.md

Design choices worth copying:

App.config and ConfigurationManager

.NET Framework apps keep settings in App.config (Web.config for ASP.NET), an XML file read with System.Configuration.ConfigurationManager. In .NET 10 this is available as the System.Configuration.ConfigurationManager NuGet package, which makes porting old code easier. The SDK copies App.config to the output as <AssemblyName>.dll.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="AppName" value="Inventory" />
    <add key="MaxItems" value="250" />
  </appSettings>
  <connectionStrings>
    <add name="Default"
         connectionString="Server=.;Database=Inventory;Integrated Security=true"
         providerName="Microsoft.Data.SqlClient" />
  </connectionStrings>
</configuration>
// dotnet add package System.Configuration.ConfigurationManager
using System.Configuration;

string? name = ConfigurationManager.AppSettings["AppName"];
int maxItems = int.Parse(ConfigurationManager.AppSettings["MaxItems"] ?? "100");
ConnectionStringSettings? cs = ConfigurationManager.ConnectionStrings["Default"];

Console.WriteLine($"{name} {maxItems}");
Console.WriteLine($"{cs?.ConnectionString} ({cs?.ProviderName})");

// the file is read from <assembly>.dll.config next to the program
Configuration file = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine(Path.GetFileName(file.FilePath));
Inventory 250
Server=.;Database=Inventory;Integrated Security=true (Microsoft.Data.SqlClient)
Legacy.dll.config

This needs a regular project (.csproj), not a file-based app. Values are untyped strings, there's no layering with environment variables, and sections like <system.web> or <system.serviceModel> have no effect in .NET 10. For new code use Microsoft.Extensions.Configuration. It can even be adopted gradually in old apps, because it doesn't depend on hosting or ASP.NET.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents