65

I try to create a .NET 6 Console Application but having troubles reading my appsettings.json file. In a web application I could use this...

var builder = WebApplication.CreateBuilder(args);

But what would I use in a console application? I get this error when trying to add it to program.cs. "The name 'WebApplication' does not exist in the current context"

6

8 Answers 8

82

Add these two nuget packages in your application

Microsoft.Extensions.Configuration

Microsoft.Extensions.Configuration.Json

Then you can use ConfigurationBuilder to use appsettings.json file

var configuration =  new ConfigurationBuilder()
     .AddJsonFile($"appsettings.json");
            
var config = configuration.Build();
var connectionString = config.GetConnectionString("ConnectionString");

Getting Values from AppSettings in Console Application

Adding AppSettings in .net core app

5
  • 1
    I tried your approach but that does not work. I get "The name 'builder' does not exist in the current context" error?
    – MTplus
    Apr 21, 2022 at 12:34
  • It will be configuration.Build(); I corrected it in my code
    – Amit Kotha
    Apr 21, 2022 at 12:37
  • 2
    Don't forget to include appsettings.json when building (Properties -> Copy to Output Directory)
    – rlv-dan
    Sep 22, 2022 at 12:41
  • 3
    Don't need both nugets. Just Microsoft.Extensions.Configuration.Json because that package implicitly uses Microsoft.Extensions.Configuration already 😎
    – Pure.Krome
    Jan 16 at 0:27
  • i have error: System.IO.FileNotFoundException: "The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was 'C:\work\CheckerHistory\CheckerHistory\CheckerHistory\bin\Debug\net7.0\appsettings.json'." But including appsettings.json when building (Properties -> Copy to Output Directory) helps.
    – mathewsun
    Mar 5 at 10:32
30

Link to docs: https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

Nuget packages are needed to do it:

<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />

using Microsoft.Extensions.Configuration;

    // Build a config object, using env vars and JSON providers.
    IConfiguration config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
    
    // Get values from the config, given their key and their target type.
    Settings settings = config.GetRequiredSection("Settings").Get<Settings>();
    
    // Write the values to the console.
    Console.WriteLine($"KeyOne = {settings.KeyOne}");
    Console.WriteLine($"KeyTwo = {settings.KeyTwo}");
    Console.WriteLine($"KeyThree:Message = {settings.KeyThree.Message}");

// Application code which might rely on the config could start here.
// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Oh, that's nice...

JSON File (appsettings.json)

{
    "Settings": {
        "KeyOne": 1,
        "KeyTwo": true,
        "KeyThree": {
            "Message": "Oh, that's nice..."
        }
    }
}

UPD: I checked the approach, and it works; My code:

// See https://aka.ms/new-console-template for more information

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

Console.WriteLine("Hello, World!");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration c = configurationBuilder.AddJsonFile("appsettings.json").AddEnvironmentVariables().Build();
var k = c.GetRequiredSection("Settings").Get<Settings>().KeyOne;
var n = 1;

public class NestedSettings
{
    public string Message { get; set; } = null!;
}
public class Settings
{
    public int KeyOne { get; set; }
    public bool KeyTwo { get; set; }
    public NestedSettings KeyThree { get; set; } = null!;
}




17

Using .NET 6 Console app, try:

using IHost host = Host.CreateDefaultBuilder(args).Build();

IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

string con= config.GetValue<string>("ConnectionStrings:conn1");
//OR
string connectionString = config["ConnectionStrings:conn1"];

Console.WriteLine($"Hello, World! {connectionString}");

appsettings.json (Properties): (CopyToOutputDirectory = Always):

"ConnectionStrings": {
    "conn1": "Server=localhost;Database=MyDatabase;Trusted_Connection=True", 
  }
4
  • I am a little confused why this is accepted but unpopular, and how it doesn't reference the JSON file-name.
    – Mr. Boy
    Nov 16, 2022 at 11:56
  • Also IMO secrets like this should not be contained in a json file (esp. if its checked into source control). This is what user secrets is for.
    – Rippo
    Nov 22, 2022 at 15:50
  • 1
    What is Host in desktop app or console app ?
    – Kiquenet
    Aug 17 at 11:09
  • @Mr.Boy I guess if you are also using Host.CreateApplicationBuilder() for dependency injection stuff, you can use this answer to get IConfiguration via: host.Services.GetRequiredService<IConfiguration>(). Otherwise you can use the other answer which uses ConfigurationBuilder instead.
    – JohnB
    Oct 12 at 3:06
6

In a console app I add the appsettings.json and user secrets like this, you may also have a development json file as well.

internal class Program
{
    internal static IConfigurationRoot Configuration;

    public static void Main()
        => new Program().MainAsync().GetAwaiter().GetResult();

    private async Task MainAsync()
    {
        var configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        configurationBuilder.AddUserSecrets(typeof(Program).GetTypeInfo().Assembly, optional: false);
        Configuration = configurationBuilder.Build();

        ...
    }
}

Then elsewhere in the console app in any class you can simply call it like this

var someSetting = Program.Configuration["SomeSetting"];

If you want a strongly typed class then see this answer .net core Console application strongly typed Configuration on SO

1
  • 2
    Main method supports async Task, my advice is to don't use GetAwaiter().GetResult()
    – Krusty
    Aug 18, 2022 at 9:02
4

I would prefer the following code because it will automatically read the appsettings.json file from the project directory. Pay attention to _.Configuration I used during configuring DbContext to read the connection string.

var builder = Host.CreateDefaultBuilder(args)
        .ConfigureServices(
                (_, services) => services
                    .AddTransient<IService, Service>()
                    .AddDbContext<ApplicationDbContext>(options =>
                        options.UseNpgsql(
                      _.Configuration.GetConnectionString("DefaultConnection"),
                            b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)))
                    );
var host = builder.Build();


var dbContext = host.Services.GetRequiredService<ApplicationDbContext>();

I put this together from this link: https://bjdejongblog.nl/net-core-6-dependency-injection-console-program/

1
  • How-to use configuration in library class dependencies?
    – Kiquenet
    Aug 17 at 11:10
1

Install the following packages

Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Hosting

create a file call appsettings.json

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "defaultConnection": "data source=.;initial catalog=ExchangeGatewayDb;integrated security=true;MultipleActiveResultSets=True;"
  }
}

add this code to Programe.cs

var hostBuilder = new HostBuilder().ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        }).ConfigureAppConfiguration((context, builder) =>
        {
            var env = context.HostingEnvironment;
            builder.SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();

            var configuration = builder.Build();
            var connectionString = configuration["ConnectionStrings:defaultConnection"];
        }).ConfigureServices(services =>
        {
            services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
            //your code
        });

var buildHost = hostBuilder.Build();
buildHost.Run();
4
  • Tried this and the program is always stuck on buildHost.Run()
    – Esko
    Oct 3, 2022 at 10:18
  • You should do your operation in the ConfigureServices method Oct 3, 2022 at 11:49
  • If you make a new .net 6 console application there is no ConfigureServices-method.
    – Esko
    Oct 3, 2022 at 12:51
  • @esko how-to use with net 6 console?
    – Kiquenet
    Aug 17 at 11:50
0

I use in my MyApp.Core library, in a ConfigMyApp class:

         public static IConfigurationRoot GetIConfigurationRoot(string outputPath = null)
        {
            var path1 = Directory.GetCurrentDirectory();
            //_configuration =
            var config = new ConfigurationBuilder()
                .SetBasePath(path1)
                .AddJsonFile("appsettings.json").Build();
            return config;
            //return new ConfigurationBuilder()
            //    .SetBasePath(outputPath)
            //    .AddJsonFile("appsettings.json", optional: true)
            //    //.AddUserSecrets("e3dfcccf-0cb3-423a-b302-e3e92e95c128")
            //    .AddEnvironmentVariables()
            //    .Build();
        }

        public static string CONEXION_SQL
        {
            get
            {
                var config = GetIConfigurationRoot();
                return config.GetConnectionString(KeyConexionMyApp);
                //return ConfigurationManager.ConnectionStrings[KeyConexionMyApp].ConnectionString;
            }
        }

Usage:

var myConnectionSQL = ConfigMyApp.CONEXION_SQL;

Use static constructor:

public static partial class ConfigMyApp
{
    static readonly IConfigurationRoot config;
    static ConfigMyApp()
    {
        config = GetIConfigurationRoot();
    }
0
  1. you need to create appSetting.json file and set Property Copy Output Directory - copy always

2.write code as below.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MidcapERP.Kafka.Configurations;
using MidcapERP.Kafka.Services;

await CreateHostBuilder(args).RunConsoleAsync();

static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureLogging((hostContext, builder) =>
    {
        builder.ClearProviders(); // This line is optional if you want to clear the default logging providers
        builder.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
        builder.AddConsole();
        builder.AddDebug();
        builder.AddEventSourceLogger();
        builder.SetMinimumLevel(LogLevel.Warning);
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddOptions();
        services.Configure<KafkaConfiguration>(hostContext.Configuration.GetSection(nameof(KafkaConfiguration)));
        services.AddHostedService<KafkaConsumerService>();
    })
    .UseConsoleLifetime(); // This line should be the last one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.