If you want add configuration file into your Console Application using .NET Core, this tutorial is for you 😉


DISCLAMER
You can find in the Internet more solutions. Let me know, if there is something wrong with my solution. 😉

Let’ start

  • First, add new NuGet packages in your project:
$ dotnet add package Microsoft.Extensions.Configuration.Binder 
$ dotnet add package Microsoft.Extensions.Configuration.Json 
  • Add new file to your project. Let’s say, it will be appsettings.json.

  • Next step, you can do in two ways:

    1. In VS. (1) Rightclick on your config file (here: appsettings.json), then (2) click on Properties. (3) In properties window, select Copy if newer from list Copy to Output Directory. These steps with numbers, are shown on screenshot below: *File not found! Screenshot image: appsettings.json configuration in VS*

    2. In .csproj file. Add below code, as child of <Project>:

<ItemGroup>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>
  • Create new class:
class ApplicationSettings
{
    public string Name { get; set; }

    public string Nick { get; set; }
}
  • Fill JSON with values:
{
  "appsettings": {
    "name": "Marcin",
    "nick": "Kalik Dev"
  }
}
  • And now write code in Main() or other method. The following snipped reads configuration file, gets section named appsettings, create object based on class ApplicationSettings and then write to console read value:
public static void Main()
{
  IConfigurationRoot configurationRoot = new ConfigurationBuilder()
      .SetBasePath(System.IO.Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json")
      .Build();

  ApplicationSettings appConfig = configurationRoot.GetSection("appsettings").Get<ApplicationSettings>();

  Console.WriteLine($"{appConfig.Name} -> {appConfig.Nick}");
}



That’s all folks! 🐻