3

How do I return an string[] from the IConfigurationRoot object?

File exists and is set to copy to output

Code

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("settings.json", optional: false, reloadOnChange: false);
_configuration = builder.Build();

var arr = _configuration["stringArray"]; // this returns null
var arr1 = _configuration["stringArray:0"]; // this works and returns first element

Settings.json

{
  "stringArray": [
    "myString1",
    "myString2",
    "myString3"
  ]
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
user3953989
  • 1,844
  • 3
  • 25
  • 56

1 Answers1

9

Use the GetValue<TResult> extension to get the value of the section.

// Requires NuGet package "Microsoft.Extensions.Configuration.Binder"
var array = _configuration.GetValue<string[]>("stringArray");

Or try binding to the section

var values = new List<string>();
_configuration.Bind("stringArray", values);

Alternatively ConfigurationBinder.Get<T> syntax can also be used, which results in more compact code:

List<string values = _configuration.GetSection("stringArray").Get<string[]>();

Reference Configuration in ASP.NET Core: Bind to an object graph

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 3
    Thanks! The 2nd method works. Also, just to comment here, it's disheartening to need 3 external nuget packages just to read text from a file, then another one just to get the info from it. Seems like this is way over-complicated. – user3953989 Jun 06 '18 at 19:11
  • 2
    The 1st method seems intuitive, but returns `null` for me. The 3rd one works. – Josef Bláha Jan 18 '22 at 22:39