====== Add Settings File to .NET Console Application ======
===== App Settings File =====
Create appsettings.json file in project root. Example contents:
{
"Settings": {
"Title": "My Application",
"Timeout": 30
}
}
===== Packages / Project Output =====
Add the following packages to the project's .csproj file:
Add the following directive to copy the appsettings file with the binary:
Always
===== Settings Class =====
Create a class to hold the settings:
public sealed class AppSettings
{
public required string Title { get; set; }
public required int Timeout { get; set; }
}
===== Initialize Configuration =====
Initialize the configuration, and retrieve the settings:
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
AppSettings appSettings = config.GetRequiredSection("Settings").Get();
===== Access Settings =====
Access the settings:
var title = appSettings.Title;
var timeout = appSettings.Timeout;
===== Alternate Access Method =====
If you use this method exclusively, you don't need the settings class.
var title = config.GetValue("Settings:Title");
var timeout = config.GetValue("Settings:Timeout");
{{tag>dotnet}}