VSCode上で開発してます。
上記記事だと一部不足していたので補足。
追加で以下パッケージをインストール。
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"]
などとやっても取得できない
下記パッケージを追加でインストール
PS> dotnet add package Microsoft.Extensions.Configuration.Binder
下記のように取得
var myArray = conf.GetSection("DIR_LIST").Get<string[]>();
すっごく気持ち悪い
参考: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>