当前位置: 移动技术网 > IT编程>开发语言>.net > .net core 灵活读取配置文件

.net core 灵活读取配置文件

2019年02月20日  | 移动技术网IT编程  | 我要评论

闽南网健康,芋头,如何安装win7系统

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);
        }
    }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网