如何在appSettings.json中硬编码和读取字符串数组?

时间:2017-03-17 13:04:47

标签: c# .net-core appsettings

我使用VSCode和NetCore 1.1.1。

我需要在appsetting.json中存储几个数据路径,让我的控制台应用程序知道在哪里查找数据。

这是appsettings.json文件的摘录:

{

    "ConnectionStrings":

    {

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

    "Data":

    {

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

    }
}

我加载配置文件,我想要"文件夹"存储在变量中的数组:

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 NULL

如果我将appsetting.json更改为仅指向这样的单个目录,那么一切正常:

{

    "ConnectionStrings":

    {

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

    "Data":

    {

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

dataFolder =" E:/ Data / Folder1 / "

所以问题似乎是它不像字符串数组,但对我来说它看起来像一个有效的Json字符串数组。我该如何修改我的appsettings(或我的C#代码)来修复它?

2 个答案:

答案 0 :(得分:34)

一个部分的索引器通过精确的密钥匹配返回字符串,并且因为数组值具有带后缀的键,所以没有任何东西可以匹配给定的密钥,并且您将获得null。

为了让它起作用,你可以使用类似的东西

from itertools import chain, combinations

qs = {"Q1":5, "Q2":1, "Q3": 1, "Q4": 4}

min_set_size = 2
max_set_size = 3

min_score = 1
max_score = 4

qs_between = [question for question, score in qs.items() if min_score <= score <= max_score]

def subsets(iterable, min_set_size, max_set_size):
    return chain.from_iterable(combinations(iterable, size)
        for size in range(min_set_size, max_set_size + 1))

result = list(subsets(qs_between, min_set_size, max_set_size))

print(result)

并检查this以获取更多选项。

答案 1 :(得分:8)

来自这里的原始答案: https://stackoverflow.com/a/42169474/7263255

像这样工作:

var someArray = configuration
   .GetSection("SomeArray")
   .GetChildren()
   .Select(x => x.Value)
   .ToArray();