欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core 灵活读取配置文件

程序员文章站 2022-06-30 12:03:14
``` using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; ``` ``` public static class Configs { p... ......
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);
        }
    }