[英]How to get an array from appsettings.json file in .Net 6?
我已经阅读了这篇关于如何在 .Net 6 控制台应用程序中访问appsettings.json
文件的优秀 SO 帖子。
但是,在我的 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"
],
如果我这样做,我会得到结果:
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"];
但是我不想将实际上是数组的内容编码为单独的代码行,如图所示。
我想做这个:
string[] logFiles = config["logFilePaths"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
但它在config["logFilePaths"]
上给我一个错误,说它是null
。
为什么那会是空的?
一种选择是安装Microsoft.Extensions.Configuration.Binder
nuget 并使用Bind
(不要忘记为appsettings.json
CopyToOutputDirectory
:
var list = new List<string>();
config.Bind("logFilePaths", list);
另一个 - 通过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.