.net core 靈活讀取配置檔案

HANFAN發表於2019-02-19
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
  public static class Configs
    {
        private const string DefaultConfigName = "appsettings.json";
        public  class ConfigCache
        { 
            internal static readonly IConfigurationRoot ConfigRoot = null;
            static  ConfigCache()
            {
                try
                { 
                    string pathToContentRoot = Directory.GetCurrentDirectory();

                    string configFilePath = Path.Combine(pathToContentRoot, DefaultConfigName);

                    if (!File.Exists(configFilePath)) 
                    {
                        throw new FileNotFoundException($"{DefaultConfigName}配置檔案不存在!");
                    }
                    //用於構建基於鍵/值的配置設定,以便在應用程式中使用
                    IConfigurationBuilder builder = new ConfigurationBuilder()
                    .SetBasePath(pathToContentRoot)//將基於檔案的提供程式的FileProvider設定為PhysicalFileProvider基本路徑
                    .AddJsonFile(DefaultConfigName, optional: false, reloadOnChange: true)//在構建器的路徑中新增JSON配置提供程式
                    .AddEnvironmentVariables();//新增讀取的Microsoft.Extensions.Configuration.IConfigurationProvider來自環境變數的配置值 

                    ConfigRoot = builder.Build();
                    
                }
                catch (Exception)
                {
                    
                }
                finally
                {
                    
                }   
            }

        }
       
        public static T Get<T>(string name, T defaultValue)
        {
            if (ConfigCache.ConfigRoot == null)
            {
                // throw new NullReferenceException("配置檔案載入異常!"); 
                return defaultValue;  
            }  
            IConfigurationSection section = ConfigCache.ConfigRoot.GetSection(name);
            
            if (section == null)
            {
                throw new KeyNotFoundException($"{name}節點不存在!");
            }
            var config = section.Get<T>();
            if (config == null)
                return defaultValue;

            return config; 
        }
        public static T Get<T>(string name)
        {
            return Get<T>(name, default);
        }
    }

相關文章