How to hardcode and read a string array in appSettings.json?

nico9T picture nico9T · Mar 17, 2017 · Viewed 24.6k times · Source

I use VSCode and NetCore 1.1.1.

I need to store several datapaths in my appsetting.json to let my console application know where to look for its data.

This is an extract of the appsettings.json file:

{

    "ConnectionStrings":

    {

        "Database": "Filename=./Data/Database/securities_master.db"
    },

    "Data":

    {

     "Folders": ["E:/Data/Folder1/","E:/Data/Folder2/"]

    }
}

I load the configuration file and I want the "Folders" array stored in a variable:

const string APP_SETTINGS_SECTION = "Data";
const string APP_SETTINGS_KEY = "Folders";

var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var configuration = builder.Build();
var dataFolders = configuration.GetSection(APP_SETTINGS_SECTION)[APP_SETTINGS_KEY];

dataFolders is NULL!

If I change my appsetting.json to point only to a single directory like this, everything works:

{

    "ConnectionStrings":

    {

        "Database": "Filename=./Data/Database/securities_master.db"
    },

    "Data":

    {

     "Folders": "E:/Data/Folder1/"   
    }
}

dataFolder = "E:/Data/Folder1/"

So the problem appears to be it doesn't like the string array but to me it looks like a valid Json string array. How should I modify my appsettings (or my C# code) to fix this?

Answer

THTP picture THTP · Mar 17, 2017

Indexer of a section returns string by exact key match, and since array values have keys with postfixes, there is nothing to match given key and you are getting null.

To get it work you may use something like this

var section = configuration.GetSection($"{APP_SETTINGS_SECTION}:{APP_SETTINGS_KEY}");
var folders = section.Get<string[]>();

And check this for more options.