For a .NET Core 2.0 console app, I did the following:
- Create a new file named appsettings.json at the root of the project (the file name can be anything)
- Add my specific settings to that file as json. For example:
{
"myKey1" : "my test value 1",
"myKey2" : "my test value 2",
"foo" : "bar"
}
Configure to copy the file to the output directory whenever the project is built (in VS -> Solution Explorer -> right-click file -> select 'Properties' -> Advanced -> Copy to Output Directory -> select 'Copy Always')
Install the following nuget package in my project:
- Microsoft.Extensions.Configuration.Json
Add the following to Program.cs (or wherever Main()
is located):
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
// rest of code...
}
Then read the values using either of the following ways:
string myKey1 = configuration["myKey1"];
Console.WriteLine(myKey1);
string foo = configuration.GetSection("foo").Value;
Console.WriteLine(foo);
More info: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration#simple-configuration
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…