2

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?

2 Answers 2

5

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

string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();
Sign up to request clarification or add additional context in comments.

2 Comments

CS1061 'IConfigurationSection' does not contain a definition for 'Get' and no accessible extension method 'Get' accepting a first argument of type
@Fandango68 install Microsoft.Extensions.Configuration.Binder as in my answer.
3

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>>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.