A Guide to Use Configuration in .Net Core Console Application

When working with .NET Core console applications, you may often need to store settings such as connection strings, API keys, or custom values. In .Net framework, the app.config file gets included automatically. While in .Net core you need to perform couple of steps to use the application configurations.

In this post, I’ll walk you through how to:

  • Create an appsettings.json file
  • Load configuration in a .NET Core console app
  • Read values (simple values + nested sections)

1. Create a .NET Core Console Application

Open your terminal or Visual Studio and create a new console app:

dotnet new console -n ConfigDemo<br>cd ConfigDemo

Your project will have a simple Program.cs with a Main method.

2. Add the Configuration Packages (for .NET Core 3.1)

Install these packages:

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables

3. Add the appsettings.json File

Create a file named appsettings.json in the project root:

{
  "ApplicationName": "My Console App",
  "Version": "1.0",
  "Logging": {
    "LogLevel": "Information",
    "EnableConsole": true
}

Important:

In Visual Studio, set its properties to:

  1. Copy to Output Directory -> Copy if newer
  2. Build Action -> Content

4. Read Configuration in Program.cs

Open Program.cs and modify it like this:

using System;
using Microsoft.Extensions.Configuration;

class Program
{
  static void Main(string[] args)
  {
  // Build configuration
    var config = new ConfigurationBuilder()
      .SetBasePath(AppContext.BaseDirectory)
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .Build();
    
      // Reading simple values
      string appName = config["ApplicationName"];
      string version = config["Version"];
  
      Console.WriteLine($"App Name: {appName}");
      Console.WriteLine($"Version: {version}");
  
      // Reading nested values using section
      string logLevel = config["Logging:LogLevel"];
      string enableConsole = config["Logging:EnableConsole"];
  
      Console.WriteLine($"Log Level: {logLevel}");
      Console.WriteLine($"Console Logging: {enableConsole}");
  }
}

Output:

App Name: My Console App
Version: 1.0
Log Level: Information
Console Logging: True

Home » A Guide to Use Configuration in .Net Core Console Application