Appsettings.json in a .NET Core Console Application

This was originally written for .NET Core 2.0, but it should work in newer versions of .NET, and is the equivalent of the old app.config and ConfigurationManager pattern. Below are the steps to set it up. This is a modified version of Ray Vega's answer on stackoverflow.

  1. Create a file named appsettings.json at the project root. (The filename can actually be anything, and is referenced below, but appsettings.json is a good convention.)
  2. Add your settings to that file in JSON format. Note that the file is much more flexible than the old app.config, and this is just an option. I currently prefer to have an AppSettings section here:
{
    "AppSettings": {
        "Key1": "KeyValue1",
        "Key2": "KeyValue2"
    }
}
  1. Set appsettings.json to be copied to the output directory if there have been any changes, since we'll load it from the default path below (in Visual Studio, right click the file, and choose Properties. Then under the advanced section in the window, set Copy to output directory to Copy if newer):
    Copy if newer settings in Visual Studio
  2. Install these two NuGet packages:
    Microsoft.Extensions.Configuration.Json
    Microsoft.Extensions.Options.ConfigurationExtensions
  3. Add an AppSettings.cs file to your project with a class and properties that match the names you added in the JSON file above. For example:
public class AppSettings
{
	public string Key1 { get; set; }
	public string Key2 { get; set; }
}
  1. And add the following code to Main in Program.cs, or factored out into a separate function (note the filename "appsettings.json" below -- it should match whatever you created above):
using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace ConsoleApplication
{
	class Program
    {
    	static AppSettings appSettings = new AppSettings();
    	static void Main(string[] args)
    	{
    		var builder = new ConfigurationBuilder()
    			.SetBasePath(Directory.GetCurrentDirectory())
    			.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        
       		var configuration = builder.Build();
            
            ConfigurationBinder.Bind(configuration.GetSection("AppSettings"), appSettings);
            
            // The rest of your program here
		}
	}
}
  1. You can now access the configuration values using properties of the appSettings property, for example:
Console.WriteLine(appSettings.Key1);
Console.WriteLine(appSettings.Key2);