简体   繁体   English

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

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

I use VSCode and NetCore 1.1.1. 我使用VSCode和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. 我需要在appsetting.json中存储几个数据路径,让我的控制台应用程序知道在哪里查找数据。

This is an extract of the appsettings.json file: 这是appsettings.json文件的摘录:

{

    "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 ! dataFoldersNULL

If I change my appsetting.json to point only to a single directory like this, everything works: 如果我将appsetting.json更改为仅指向这样的单个目录,则一切正常:

{

    "ConnectionStrings":

    {

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

    "Data":

    {

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

dataFolder = " 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. 所以问题似乎是它不喜欢字符串数组,但对我来说它看起来像一个有效的Json字符串数组。 How should I modify my appsettings (or my C# code) to fix this? 我应该如何修改我的appsettings(或我的C#代码)来解决这个问题?

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. 一个部分的索引器通过精确的键匹配返回字符串,并且由于数组值具有带后缀的键,因此没有任何东西可以匹配给定的键并且您将获得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. 并查看更多选项。

Original answer from here: https://stackoverflow.com/a/42169474/7263255 原文如下: https//stackoverflow.com/a/42169474/7263255

Works like this: 像这样工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM