Search code examples
c#jsonconsole-application.net-6.0

How can I read the appsettings.json in a .NET 6 console application?


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"


Solution

  • 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", 
      }