.NET Core中使用Json文件来存储配置。在项目中新建appsettings.json文件,内容示例:

{
  "option1": "value1",
  "option2": 2,

  "subsection": {
    "suboption1": "subvalue1"
  },

  "List": [
    {
      "name": "name1",
      "count": 1
    },
    {
      "name": "name2",
      "count": 2
    }
  ]
}

读取和操作配置需要安装以下两个NuGet包。

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json

使用示例:

using System;
using Microsoft.Extensions.Configuration;

namespace ConsoleApp1
{
    class Program
    {
        public static IConfigurationRoot Configuration;

        static void Main(string[] args)
        {
            string baseDirectory = AppContext.BaseDirectory;

            var builder = new ConfigurationBuilder()
                .SetBasePath(baseDirectory)
                .AddJsonFile("appsettings.json", true, true);

            Configuration = builder.Build();

            Console.WriteLine($"option1 = {Configuration["option1"]}");
            Console.WriteLine($"option2 = {Configuration["option2"]}");
            Console.WriteLine($"suboption1 = {Configuration["subsection:suboption1"]}");

            var list = Configuration.GetSection("List").GetChildren();
            foreach(var item in list)
            {
                Convert.ToInt32(item["count"]);
            }

            Console.ReadLine();
        }
    }
}