0

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?

Fandango68
  • 4,461
  • 4
  • 39
  • 74

2 Answers2

1

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>>();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

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

string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();
0xced
  • 25,219
  • 10
  • 103
  • 255
  • CS1061 'IConfigurationSection' does not contain a definition for 'Get' and no accessible extension method 'Get' accepting a first argument of type – Fandango68 Jul 08 '22 at 06:49
  • 2
    @Fandango68 install `Microsoft.Extensions.Configuration.Binder` as in my answer. – Guru Stron Jul 08 '22 at 06:55