[英]C# CommandLineApplication Console App to read an appsettings.json file
Is there a way in C# to let a Console App to read a json file?? C# 中有没有办法让控制台应用程序读取 json 文件?
appsettings.json appsettings.json
{
"Position": {
"Title": "Editor",
"Name": "Joe Smith"
}
}
program.cs (snippets) 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);
}
Then in the apps OnExecute function然后在应用程序中 OnExecute function
protected void OnExecute() {
string arg1 = jsonSettings("Position:Title");
Console.WriteLine(arg1);
}
The variable would set the variable and output "Editor"该变量将设置变量和 output "Editor"
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" 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工作示例可以在这里找到: JsonSettingsConsleApplication
Within your application you have to add those two packages:在您的应用程序中,您必须添加这两个包:
Afterwards you have to setup the read of the file into a configuration object:之后,您必须将文件的读取设置为配置 object:
var config = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json").Build();
And then read the configuration into a matching object:然后将配置读入匹配的 object:
var section = config.GetSection(nameof(WeatherClientConfig));
var weatherClientConfig = section.Get<WeatherClientConfig>();
These code example with more details can be found here .可以在此处找到这些具有更多详细信息的代码示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.