ASP.NET Core configuration for .NET Core console application

kimsagro picture kimsagro · Jun 30, 2016 · Viewed 118.7k times · Source

ASP.NET Core support a new configuration system as seen here: https://docs.asp.net/en/latest/fundamentals/configuration.html

Is this model also supported in .NET Core console applications?

If not what is alternate to the previous app.config and ConfigurationManager model?

Answer

Ray picture Ray · Sep 27, 2017

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://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration#simple-configuration