LoginSignup
25
28

More than 5 years have passed since last update.

.NET Core のコンソ-ルアプリケーションで設定ファイルを利用する

Last updated at Posted at 2017-10-31

.NET Core のコンソ-ルアプリケーションで設定ファイルを利用する

.NET Core 2.0 で設定ファイルを利用できるようにする方法です。
環境は以下の通りです。

  • Visual Studio 2017
  • .NET Core 2.0

NuGet パッケージのインストール

設定ファイルを読み込むのに必要な NuGet パッケージをインストールします。

設定ファイルの追加

プロジェクトに Json ファイルを追加します。
ファイル名は自由ですが、自分は AppConfig.json としました。

Json ファイルを追加した後、ファイルのプロパティを以下のように変更しておきます。
( ファイルを右クリック -> [プロパティ] )

  • ビルドアクション: なし
  • 出力ディレクトリにコピー: 新しい場合はコピーする
    • この設定をしておかないと、実行ファイルにしたときに出力ディレクトリに Json ファイルが出力されず、自分でファイルをコピーしなければならなくなります。

設定の追加

追加した Json ファイルに設定を書きます。
データベースの接続設定を書く場合は、キーを ConnectionStrings にしておくとコードからの読み込みがしやすくなります。

AppConfig.json
{
    "ConnectionStrings": {
        "Default": "server=localhost;userid=root;pwd=;port=3306;database=db_test;"
    },
    "AppSettings": {
        "TestConstValue": 88
    }
}

ソースコードから設定値を読み込む

設定値を読み込むには、Microsoft.Extensions.Configuration.ConfigurationBuilder を利用して以下のように読み込みます。

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

namespace TestProject
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = GetConfiguration();

            // 設定値の取得
            var testValue = config["AppSettings:TestConstValue"];
            // 以下の書き方でも取得できます。
            testValue = config.GetSection("AppSettings")["TestConstValue"];

            // ConnectionString は専用のメソッドが用意されています。
            var connectionString = config.GetConnectionString("Default");
            // 下記の書き方でも取得できますが、専用のメソッドを利用するほうが簡単です。
            connectionString = config["ConnectionStrings:Default"];
            connectionString = config.GetSection("ConnectionStrings")["Default"];
        }


        static IConfiguration GetConfiguration()
        {
            var configBuilder = new ConfigurationBuilder();

            // 設定ファイルのベースパスをカレントディレクトリ( 実行ファイルと同じディレクトリ )にします。
            configBuilder.SetBasePath(Directory.GetCurrentDirectory());

            // Json ファイルへのパスを設定します。SetBasePath() で設定したパスからの相対パスになります。
            configBuilder.AddJsonFile(@"AppConfig.json");

            return configBuilder.Build();
        }
    }
}

参考ページ

25
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
28