Reading config from a c# console application
Console application
1. Install nuget package Microsoft.Extensions.Hosting
2.
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using IHost host = Host.CreateDefaultBuilder(args).Build();
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appSettings.json")
.AddEnvironmentVariables()
.Build();
Settings settings = config.GetRequiredSection(key: "Settings").Get<Settings>();
Console.WriteLine(settings.KeyOne);
Console.WriteLine(settings.KeyTwo);
Console.WriteLine(settings.KeyThree.Message);
foreach(var ipAddress in settings.IPAddresses)
{
Console.WriteLine(ipAddress);
}
foreach(var versions in settings.KeyThree.SupportedVersions)
{
Console.WriteLine(versions.Key);
Console.WriteLine(versions.Value);
}
Console.WriteLine(settings.KeyThree.SupportedVersions);
await host.RunAsync();
in the properties of the project add the following.
<ItemGroup>
<Content Include="appSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
appSettings.json
{
"Settings": {
"KeyOne": 1,
"KeyTwo": true,
"KeyThree": {
"Message": "Oh, that's nice",
"SupportedVersions": {
"v1": "1.0.0",
"v2": "2.0.0"
}
},
"IPAddresses": [
"46.36.198.121",
"46.36.198.122",
"46.36.198.123",
"46.36.198.124",
"46.36.198.125"
]
}
}
Comments
Post a Comment