Using an ‘appsettings.json’ file with a C# console app

To add an appsettings.json file to a C# console app:

Step 1. Add the "Microsoft.Extensions.Configuration.Json" package to the project.

Adding this package also pulls in the "Microsoft.Extensions.Configuration.Abstractions" and "Microsoft.Extensions.Primitives" packages (as of June 2022).

Step 2. Add a appsettings.json file to the root of the project.

Step 3. Right-click the appsettings.json file to show its Properties window. Then set its "Copy to Output Directory" property to "Copy always." This ensures the appsettings.json file is copied to the Debug or Release folder every time the project is built.

Figure 1. Set "Copy to Output Directory" property

Step 4. Add values to the appsettings.json file. The example below shows a couple of connection strings defined in the appsettings.json file.

Step 5. Add this using statement to your project:

Step 6. Add this bootstrap code to instance an IConfiguration object:

You can park this code away in a secondary class or use it inline. The resulting config object can then passed around to provide access to configuration values.

Step 7. Fetch values from the appsettings.json file:


Surprisingly, the keys to the values in the appsettings.json file are not case-sensitive with either technique above. However, it seems prudent to me to treat them as such.

Configuration flexibility

Using an appsettings.json file with the IConfiguration object offers lots of flexibility. For example, the configuration below:

  • Reads values from appsettings.json first
  • Then if it is present, reads any values from, overwriting, or adding to, values read from appsettings.json
  • Then, attempt to read values from environmental settings. These also overwrite or add to, the setting values previously established with the first two steps.

6 thoughts on “Using an ‘appsettings.json’ file with a C# console app”

  1. The package should be Microsoft.Extensions.Configuration.Json

    and I don’t know why you wouldn’t use config.GetConnectionString(“SqlServer”)

  2. when I have both the appsettings.json and it always reads both regardless of if I have done a Release or Debug run in Visual Studio. How do I get it to only include reading the .dev.json file in Debug mode?

  3. Thanks. That really helped me figure out how to switch from App.config to AppSettings.json. Very well explained.

  4. وائل جلال الدين

    You are the best, I was not able to create database migration until I found this article.

Leave a Comment

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