Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with configuration in C# when NOT using ASP.NET Core?

Tags:

c#

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?

like image 345
Draex_ Avatar asked Dec 07 '22 10:12

Draex_


1 Answers

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");
like image 147
AussieJoe Avatar answered Jun 10 '23 15:06

AussieJoe