Configuration files
suggest changeMost 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:
Microsoft.Extensions.Configuration: the standard configuration system used by ASP.NET Core and the Generic Host. It readsappsettings.json(and XML, INI, environment variables, command-line arguments, secrets) into one key/value tree and binds it to your classes.- Your own JSON file with
System.Text.Json: best for per-user settings that the program also writes back, like window position or recently opened files. App.configandConfigurationManager: the .NET Framework way. Still works in .NET 10 through a NuGet package, mainly for porting old code.
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:
- The indexer
config["key"]returnsstring?. A missing key givesnull, not an exception. GetValue<T>(key, default)converts with the type'sTypeConverterand returns the default if the key is missing. It comes from theBinderpackage.GetSectionnever returnsnull. For a missing section you get an empty one, so checkExists()when it matters.GetConnectionString("Default")is shorthand forconfig["ConnectionStrings:Default"].- Keys are case-insensitive:
config["database:host"]works too.
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
Get<T>()creates a new instance and returnsnullif the section is empty.Bind(obj)fills an object you already have.- Properties need a public setter, or a constructor parameter with a matching name (records work).
- Collections (
List<T>, arrays,Dictionary<string, T>), nested objects, enums,TimeSpan,Uri,Guidand the usual primitives are supported. - Property initializers act as defaults: keys missing from the file leave them alone.
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:
appsettings.json: defaults, checked into source controlappsettings.{Environment}.json: overrides forDevelopment,Staging,Production- environment variables: per-machine or per-container values, secrets
- 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:
- In environment variable names
__(double underscore) stands for:, because:isn't allowed in variable names on all platforms. The prefix is stripped. See Environment variables for details. - Command-line arguments accept
--Key value,--Key=value,/Key valueandKey=value. Nested keys use:, like--Database:Port 6543. Command-line arguments covers parsing beyond simple overrides. - Arrays merge by index, not by replacement. If
appsettings.jsonhas 3 elements and an override has 1, you get the override's element 0 plus the original elements 1 and 2.
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:
- Location.
SpecialFolder.ApplicationDatais%APPDATA%on Windows and~/.configon Linux and macOS. Never write next to the executable: on WindowsProgram Filesisn't writable, and a reinstall would wipe the settings. UseSpecialFolder.LocalApplicationDatafor caches and machine-specific data. - Defaults in code. Property initializers provide defaults, so a missing file or a missing property just works. New settings added in a later version get their default when an old file is loaded.
- Atomic save. Writing to a temporary file and moving it over the old one means a crash or power loss leaves either the old or the new file, never a truncated one.
- Tolerant reading. Comments and trailing commas make hand-editing less error-prone. Decide what to do with a corrupt file: here a
JsonExceptionpropagates, which you might catch to fall back to defaults after renaming the bad file. - Source generation.
JsonSerializerContextavoids reflection. File-based apps and Native AOT apps disable reflection-basedSystem.Text.Jsonserialization, so without the contextJsonSerializer.Serialize(this)throwsInvalidOperationException.
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
- Use
Microsoft.Extensions.Configurationfor app settings and aSystem.Text.Jsonfile for settings the user changes from inside the app. - Commit defaults, not secrets.
appsettings.jsonholds safe defaults. Passwords and API keys come from environment variables, user secrets or a secret store. - Bind to typed classes and validate at startup with
ValidateOnStart, so a wrong value fails fast with a clear message instead of a confusing error later. - Turn on
ErrorOnUnknownConfiguration(or check withGetDebugView()) when a setting seems to be ignored. Usually the key is misspelled or a later source overrides it. - Mind the base path. Relative file names are resolved against
AppContext.BaseDirectoryby default, and against the content root (the current directory) in the Generic Host. Copy config files to the output directory in projects. - Don't pass
IConfigurationeverywhere. Read and bind it once inMainor at DI registration, and give the rest of the code plain options objects.