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
Step 5. Add this
using statement to your project:
Step 6. Add this bootstrap code to instance an
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
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.
appsettings.json file with the
IConfiguration object offers lots of flexibility. For example, the configuration below:
- Reads values from
- Then if it is present, reads any values from
appsettings.dev.json, overwriting, or adding to, values read from
- Then, attempt to read values from environmental settings. These also overwrite or add to, the setting values previously established with the first two steps.
3 thoughts on “Using an ‘appsettings.json’ file with a C# console app”
The package should be Microsoft.Extensions.Configuration.Json
and I don’t know why you wouldn’t use config.GetConnectionString(“SqlServer”)
Exactly, but then you would need to use the key “ConnectionStrings” (plural).
when I have both the appsettings.json and appsettings.dev.json 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?