简体   繁体   English

如何从 .Net 6 中的 appsettings.json 文件中获取数组?

[英]How to get an array from appsettings.json file in .Net 6?

I've read this excellent SO post on how to get access to the appsettings.json file in a .Net 6 console app.我已经阅读了这篇关于如何在 .Net 6 控制台应用程序中访问appsettings.json文件的优秀 SO 帖子

However, in my json file I have several arrays:但是,在我的 json 文件中,我有几个数组:

"logFilePaths": [
    "\\\\server1\\c$\\folderA\\Logs\\file1.log",
    "\\\\server2\\c$\\folderZ\\Logs\\file1A1.log",
    "\\\\server3\\c$\\folderY\\Logs\\file122.log",
    "\\\\server4\\c$\\folderABC\\Logs\\fileAB67.log"
  ],

And I get the results if I do something like this:如果我这样做,我会得到结果:

    var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
    var config = builder.Build();

    string logFile1 = config["logFilePaths:0"];
    string logFile2 = config["logFilePaths:1"];
    string logFile3 = config["logFilePaths:2"];

But I don't want to have to code what is effectively an array into separate lines of code, as shown.但是我不想将实际上是数组的内容编码为单独的代码行,如图所示。

I want to do this:我想做这个:

string[] logFiles = config["logFilePaths"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

But it gives me an error on config["logFilePaths"] saying it's null .但它在config["logFilePaths"]上给我一个错误,说它是null

Why would that be null?为什么那会是空的?

One option is to install Microsoft.Extensions.Configuration.Binder nuget and use Bind (do not forget to setup CopyToOutputDirectory for appsettings.json ):一种选择是安装Microsoft.Extensions.Configuration.Binder nuget 并使用Bind (不要忘记为appsettings.json CopyToOutputDirectory

var list = new List<string>();
config.Bind("logFilePaths", list);

Another - via GetSection (using the same nuget to bind a collection):另一个 - 通过GetSection (使用相同的 nuget 绑定集合):

var list = config.GetSection("logFilePaths").Get<List<string>>();

要将logFilePaths作为数组访问,您需要使用Get<T>扩展方法:

string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM