Adding appsettings.json to a .NET Core console app

This is something that strangely doesn’t seem to be that well documented and took me a while to figure out though in the end it’s pretty simple.

All that’s required is to add the following NuGet packages and an appsettings.json file.

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

The appsettings.json files “Copy to Output Directory” property should also be set to “Copy if newer” so that the application is able to access it when published.

The settings are injected in the main method rather than in the startup method as with web apps but the code is essentially the same.


        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();

            Console.WriteLine(configuration.GetConnectionString("Storage"));
        }

An example of this in action can be seen here.

In the case of receiving the error “IConfigurationBuilder does not contain a definition for AddJsonFile” just rebuild the project and close and re-open Visual Studio.


6 Comments

Sergey · 17th March 2018 at 10:28 am

Thank you for sharing this!

gerardo · 22nd March 2018 at 8:01 pm

cool post! heads up i had to set appsettings.json property Copy to Output Directory to Copy If Newer for mine to work

    Shinigami · 23rd March 2018 at 9:44 am

    Thanks Gerardo, I always forget about this! Have updated the post to mention it.

murat mert · 10th April 2018 at 3:31 pm

hi,
what if there are other enviroments, i mean how can i distinguish other environments like “appsettings.*.json”.Another question does support array value of key.

    Shinigami · 11th April 2018 at 9:35 am

    Hi Murat,
    The below is used in the web application template to load the settings based on the environment.

    .AddJsonFile($”appsettings.{Environment.GetEnvironmentVariable(“ASPNETCORE_ENVIRONMENT”) ?? “Production”}.json”, optional: true)

    It looks like System.Enviroment is usable in console applications so you may be able to use this to determine what enviroment your application is running in.

PinoyDev · 9th May 2018 at 4:00 pm

Thank you so much for this!! great help

Leave a Reply

Your email address will not be published. Required fields are marked *