Reading a JSON configuration file in .Net Core

By | May 29, 2018

Below is a very basic and short example of how to read settings from a JSON configuration file in .Net Core.

Required NuGet packages

The following .Net Core NuGet packages will need to be added to your project.

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

The JSON sample file

For the example I use the following JSON file which I called sample.json.

{
“Setting1”: “ABC”,
“Setting2.X”: “123”,
“Setting2.Y”: “456”
}

How to load the JSON configuration file in .Net Core

Below is a very basic code snippet showing how to load the file. The Method below returns a IConfigurationRoot interface which will allow you interrogate the loaded file.

Things to note from this example:

  • The JSON file in this example is found in the root folder of the application.
  • The JSON file is required to be present in the solution. (This is controlled with one of the bool settings in the example.)
  • If the JSON file is modified outside of the application the file will be re-read.(This is controlled with one of the bool settings in the example.)

private static IConfigurationRoot ReadJsonConfiguration(string filename)
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(filename, false, true)
.Build();
}

How to read values from the JSON configuration file in .Net Core

IConfigurationRoot configuration = ReadJsonConfiguration(“sample.json”);
string value1 = configuration[“Setting1”];
string value2 = configuration[“Setting2.X”];
string value3 = configuration[“Setting2.Y”];

Leave a Reply

Your email address will not be published.