11 | Configuration File Provider: the freedom to choose the format configuration
Configuration File Provider
- Microsoft.Extensions.Configuration.Ini
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.Configuration.NewtonsoftJson
- Microsoft.Extensions.Configuration.Xml
- Microsoft.Extensions.Configuration.UserSecrets
These are needed to read a different file formats, or to read the file from different locations
File provider supports
- If the file Optional
- Monitoring file changes
By following the code to understand these properties
Source link:
https://github.com/witskeeper/geektime/tree/master/samples/ConfigurationFileDemo
References the following four packages:
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Abstractions
- Microsoft.Extensions.Configuration.Ini
- Microsoft.Extensions.Configuration.Json
Read appsettings.json
{
"Key1": "Value1",
"Key2": "Value2"
}
The main program
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json");
var configurationRoot = builder.Build();
Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
Console.ReadKey();
Start the program, the output is as follows:
Key1:Value1
Key2:Value2
Key3:
Key3 does not exist, so his value is empty
If the file is its optional second parameter optional, default is false
builder.AddJsonFile("appsettings.json", optional:false);
This means that when the file does not exist it will complain
It's another argument is reloadOnChange, default is true
builder.AddJsonFile("appsettings.json", optional:false, reloadOnChange:true);
This means that every time a file is changed, it will go to read the new file
Then look at the appsettings.ini
Key3=Value3 in ini
The main program
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional:false, reloadOnChange:true);
builder.AddIniFile("appsettings.ini");
var configurationRoot = builder.Build();
Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
Console.ReadKey();
Start the program, the output is as follows:
Key1:Value1
Key2:Value2
Key3:Value3 in ini
Here you can see the new configuration has been added to take effect
source is arranged to add builder sequential relationship, the configuration will be added to cover the first add arrangement
This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing.
欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。
如有任何疑问,请与我联系 ([email protected]) 。