Home > Software design >  How to get an array from appsettings.json file in .Net 6?
How to get an array from appsettings.json file in .Net 6?

Time:07-08

I've read this excellent SO post on how to get access to the appsettings.json file in a .Net 6 console app.

However, in my json file I have several arrays:

"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.

Why would that be null?

CodePudding user response:

One option is to install Microsoft.Extensions.Configuration.Binder nuget and use Bind (do not forget to setup CopyToOutputDirectory for appsettings.json):

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

Another - via GetSection:

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

CodePudding user response:

To access the logFilePaths as an array, you want to use the Get<T> extension method:

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