Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string array from core console appSettings.json file

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"
  ]
}
like image 456
user3953989 Avatar asked Jun 07 '26 17:06

user3953989


1 Answers

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

like image 178
Nkosi Avatar answered Jun 10 '26 08:06

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!