LoginSignup
7
7

More than 5 years have passed since last update.

.NET Coreで定義ファイルを読む

Last updated at Posted at 2018-10-19

VSCode上で開発してます。

.NET と.NET Coreで定義ファイルを読む

上記記事だと一部不足していたので補足。
追加で以下パッケージをインストール。

PS> dotnet add package Microsoft.Extensions.Configuration.FileExtensions

AddJsonFileの前にSetBasePathが必要。

Program.cs
IConfigurationRoot conf = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("App.Config.json", optional: true)
  .Build();

Console.WriteLine("conf: " + conf["hoge"]);

サンプルなどでは、BasePathにセットするのは上記のようになってますが、これだとexeを実行する位置によっては対象ファイルが見えなくなってしまうのでSystem.AppDomain.CurrentDomain.BaseDirectoryを指定すると良いです。

参考:c# - How to SetBasePath in ConfigurationBuilder in Core 2.0 - Stack Overflow

配列を扱う

JSONの中に下記のような配列が含まれる場合、上記だけでは不足で

{
    "ID": "406110182",
    "INPUT": "INPUT",
    "OUTPUT": "OUTPUT",
    "DIR_LIST": [
        "hoge",
        "fuga",
        "abc",
        "yahoo"
    ]
}
conf["DIR_LIST"]

などとやっても取得できない:worried:

下記パッケージを追加でインストール

PS> dotnet add package Microsoft.Extensions.Configuration.Binder

下記のように取得

var myArray = conf.GetSection("DIR_LIST").Get<string[]>();

すっごく気持ち悪い:frowning2:

参考:ASP.NET Core Get Json Array using IConfiguration - Stack Overflow

コンソールアプリを配置時に上記ファイルを含める

これだけだと、publish時にこのファイルが含まれないので、.csprojに以下設定を追加

xxx.csproj
  <ItemGroup>
    <Content Include="App.Config.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

参考:[VisualStudio]ビルド時のファイルコピー先をプロジェクト階層と違う場所にする

7
7
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
7
7