ASP.NET Core configuration for .NET Core console application

For a .NET Core 2.0 console app, I did the following:

  1. Create a new file named appsettings.json at the root of the project (the file name can be anything)
  2. Add my specific settings to that file as json. For example:
{
  "myKey1" :  "my test value 1", 
  "myKey2" :  "my test value 2", 
  "foo" :  "bar" 
}
  1. Configure to copy the file to the output directory whenever the project is built (in VS -> Solution Explorer -> right-click file -> select ‘Properties’ -> Advanced -> Copy to Output Directory -> select ‘Copy Always’)

  2. Install the following nuget package in my project:

    • Microsoft.Extensions.Configuration.Json
  3. Add the following to Program.cs (or wherever Main() is located):

    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
    
        var configuration = builder.Build();
    
        // rest of code...
    }
    
  4. Then read the values using either of the following ways:

    string myKey1 = configuration["myKey1"];
    Console.WriteLine(myKey1);
    
    string foo = configuration.GetSection("foo").Value;
    Console.WriteLine(foo);
    

More info: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration#simple-configuration

Leave a Comment