Home > Software design >  C# CommandLineApplication Console App to read an appsettings.json file
C# CommandLineApplication Console App to read an appsettings.json file

Time:01-28

Is there a way in C# to let a Console App to read a json file ??

appsettings.json

   {
       "Position": {
            "Title": "Editor",
            "Name": "Joe Smith"
       }
   }

program.cs (snippets)

 public static int Main(string[] args)
 {
     var application = new CommandLineApplication<Program>();
     application.Conventions.UseDefaultConventions();
     // something like application.AddJsonFile("appsettings.json");

     return application.Execute(args);
 }

Then in the apps OnExecute function

 protected void OnExecute() {
    string arg1 = jsonSettings("Position:Title");
    Console.WriteLine(arg1);
 }

The variable would set the variable and output "Editor"

CodePudding user response:

You can use this, it should work with some tweaks ;)

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

class Program
{
    static void Main(string[] args)
    {
        // Setup Host
        var host = CreateDefaultBuilder().Build();
            
        // Invoke Worker
        using (IServiceScope serviceScope = host.Services.CreateScope())
        {
            IServiceProvider provider = serviceScope.ServiceProvider;
            var fooService = provider.GetRequiredService<FooService>();
            ...
        }

        host.Run();
    }
    
    static IHostBuilder CreateDefaultBuilder()
    {
        return Host.CreateDefaultBuilder()
            .ConfigureAppConfiguration(app =>
            {
                app.AddJsonFile("appsettings.json");
            })
            .ConfigureServices(services =>
            {
                services.AddSingleton<FooService>();
            });
    }
}

You'll need to add the nuget package "Microsoft.Extensions.Hosting" and go to the appsettings file properties and set "copy to output directory" to "always"

Working example can be found here: JsonSettingsConsleApplication

CodePudding user response:

Within your application you have to add those two packages:

Afterwards you have to setup the read of the file into a configuration object:

var config = new ConfigurationBuilder()
    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
    .AddJsonFile("appsettings.json").Build();

And then read the configuration into a matching object:

var section = config.GetSection(nameof(WeatherClientConfig));
var weatherClientConfig = section.Get<WeatherClientConfig>();

These code example with more details can be found here.

  •  Tags:  
  • Related