Best Xciles
Xciles
2289 days ago

Console AppSettings

Using AppSettings from ASP.NET Core in a Console Application

Image Description

ASP.NET Core gives us the possibility to use appsetting.json files to manage settings. AppSettings allow us to create different files for each environment that we define or use, and allows us to override them with environment variables.

But what if you wanted to use configuration files in an ASP.NET Core way for console applications?

You can!

Usually in ASP.NET Core, the .CreateDefaultBuilder(args) in the Program class makes sure that, including other things, the configuration files are loaded. This includes both the appsettings.json files and the appsettings.{Environment}.json files.

We can use the same idea within a console application. Todo this we have to do the following:

And you are good to go!

I've created a config.json file containing the following:

{
  "MyConfig": {
    "MyFirstValue": "MyValue",
    "MySecondValue": "MySecondValue"
  }
}

To use the configuration you can do the following:

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")
            .Build();

        const string consoleParam = "MyConfig:MyFirstValue";
        Console.WriteLine($"{consoleParam}: {configuration[consoleParam]}");

        Console.ReadKey();
    }
}

I can use all things that I usually do within my console application. Get the configuration via GetSection()

var configSection = _config.GetSection("MyConfig");

Or just use a : to navigate and get item, like I did in the above example.

The nice thing about these configuration providers is that there are many of them that I can use. The usual providers, such as json, xml or ini files, but also a provider for command-line arguments. This provider will allow you to use and access command-line arguments via the configuration provider.

This one is even easier to use. After including the Microsoft.Extensions.Configuration.CommandLine nuget, instead of loading from json you can load from command-line arguments with the following:

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        var configuration = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();

        const string consoleParam = "consoleParam";
        Console.WriteLine($"{consoleParam}: {configuration[consoleParam]}");

        Console.ReadKey();
    }
}

After building the project you can either set Application arguments within the Debug tab of Visual Studio or add them when executing like this: Success!

Hope this helps!