Fandango68
Fandango68

Reputation: 4868

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?

Upvotes: 2

Views: 2929

Answers (2)

Guru Stron
Guru Stron

Reputation: 142173

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 (using the same nuget to bind a collection):

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

Upvotes: 3

0xced
0xced

Reputation: 26518

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

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

Upvotes: 4

Related Questions