c# add appsettings.json code example

Example 1: use appsettings.json in console app

All that’s required is to add the following NuGet packages and an appsettings.json file.

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json

The appsettings.json files “Copy to Output Directory” property should also be set toCopy if newer” so that the application is able to access it when published.

Example 2: appsettings in console application c#

using System;
using Microsoft.Extensions.Configuration;

namespace DiConsoleApp
{
    public class SomeService : ISomeService
    {
        IConfiguration configuration;

        public SomeService(IConfiguration configuration)
        {
            this.configuration = configuration;    
        }

        public void DoProcess()
        {
            var value = configuration["SomeKey"];
            Console.WriteLine("Value from the Config is: " + value);
        }
    }
}

Example 3: appsettings in console application c#

{
    "SomeKey": "This is from Config!"
}

Tags:

Java Example