- .Xml
- .Json
現在我要記錄的是第二種.json的格式該如何在主控台的專案使用強型別讀取。
首先,在專案的最上層新增一個appsetting.json檔案
接著,新增一個物件檔,處理設定檔的讀取。
- internal class ConfigHelp
- {
- private readonly IConfigurationRoot config;
- public ConfigHelp()
- {
- config = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsetting.json", true)
- .Build();
- }
- public void Get<T>(string configName, ref T resp)
- {
- config.GetSection(configName).Bind(resp);
- }
- public string? Get(string configName)
- {
- return config[configName];
- }
- }
appsetting.json檔案
- {
- "Setting": {
- "MinThreads": 2,
- "MaxThreads": 3,
- "TestTimes": 300
- }
- }
設定檔的DTO
- public class Setting
- {
- public int MinThreads { get; set; }
- public int MaxThreads { get; set; }
- public int TestTimes { get; set; }
- }
實際主控台程式讀取。
- internal class Program
- {
- private static Setting setting = new Setting();
- static void Main(string[] args)
- {
- ConfigHelp config = new ConfigHelp();
- config.Get
("Setting", ref setting); } }
沒有留言:
張貼留言