Search code examples
c#arraysjsonconsole-application.net-6.0

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.

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?


Solution

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

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