I'm using .NET Core 3.1.
Microsoft offers comprehensive guide about how to work with configuration for ASP.NET. However, I can't find any guide on how to use configuration in a .NET Core application, which doesn't use ASP.NET.
How do I access configuration files from C# console application?
Configuration functionality is not built in to .NET Core (obviously). You will need to inject it, using Nuget and some startup configuration. Essentially you will need to register your configuration. Here is how...
Install the NuGet packages:
Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.CommandLine
Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables
Add an appsettings.json
file to your project at the root level. You'll need to register it like so:
static async Task Main(string[] args)
{
IConfiguration Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
}
Now that your providers are registered with your console app, you can reference your configuration like so:
var section = Configuration.GetSection("MySectionOfSettings");
var configValue = Configuration.GetValue("MySetting");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With