用于读取 appsettings.json 文件的 C# CommandLineApplication 控制台应用程序

C# CommandLineApplication Console App to read an appsettings.json file

C# 中有没有办法让控制台应用程序读取 json 文件??

appsettings.json

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

program.cs(片段)

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

     return application.Execute(args);
 }

然后在应用的OnExecute函数中

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

变量将设置变量并输出“Editor”

您可以使用它,它应该可以工作 一些调整 ;)

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>();
            });
    }
}

您需要添加 nuget 包“Microsoft.Extensions.Hosting”并转到 appsettings 文件属性并将“复制到输出目录”设置为“始终”

可在此处找到工作示例:JsonSettingsConsleApplication

在您的应用程序中,您必须添加这两个包:

之后您必须将文件的读取设置到配置对象中:

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

然后将配置读入匹配对象:

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

可以在 here.

中找到具有更多详细信息的这些代码示例