備忘録

備忘録

ConfigurationBuilderを利用して設定ファイルを読み込む方法

Ⅰ. はじめに

タイトルの通り「ConfigurationBuilderを利用して設定ファイルを読み込む方法」です。

Ⅱ. やり方

1. 必要なパッケージをインストールする
Install-Package Microsoft.Extensions.Hosting
Install-Package Microsoft.Extensions.Configuration
2. サンプルプログラムを書く

appsettings.json

{
  "Key001": "value001",
  "Key002": 123,
  "Key003": [ "value001", "value002", "value003" ],
  "Key004": {
    "SubKey001": "sub_value001"
  },
  "Key005": [
    { "Id": 1, "Name": "name001", "CreatedAt": "2020/01/01 00:00" },
    { "Id": 2, "Name": "name002", "CreatedAt": "2020/01/02 00:00" },
    { "Id": 3, "Name": "name003", "CreatedAt": "2020/01/03 00:00" }
  ]
}

Program.cs

using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace Test
{
  class User
  {
    public string Name { get; set; }
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
  }

  class Program
  {
    static void Main(string[] args)
    {
      var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .Build();

      Console.WriteLine(config.GetValue<string>("Key001"));
      Console.WriteLine(config.GetValue<int>("Key002"));
      Console.WriteLine(string.Join(",", config.GetSection("Key003").Get<string[]>()));
      Console.WriteLine(config.GetValue<string>("Key004:SubKey001"));

      /*
      var users = config.GetSection("Key005").GetChildren().Select(x => new User
      {
        Id = x.GetValue<int>("Id"),
        Name = x.GetValue<string>("Name"),
        CreatedAt = x.GetValue<DateTime>("CreatedAt")
      }).ToArray();
      */

      var users = config.GetSection("Key005").Get<User[]>();
      foreach (var user in users)
      {
        Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, CreatedAt: {user.CreatedAt}");
      }
    }
  }
}

実行結果

value001
123
value001,value002,value003
sub_value001
Id: 1, Name: name001, CreatedAt: 2020/01/01 0:00:00
Id: 2, Name: name002, CreatedAt: 2020/01/02 0:00:00
Id: 3, Name: name003, CreatedAt: 2020/01/03 0:00:00