• .net core 灵活读取配置文件


    引用nuget

    Microsoft.Extensions.Configuration
    Microsoft.Extensions.Configuration.Binder
    Microsoft.Extensions.Configuration.FileExtensions
    Microsoft.Extensions.Configuration.EnvironmentVariables
    Microsoft.Extensions.Configuration.Json
    
    using Allspark.Core.Common.Json;
    using Microsoft.Extensions.Configuration;
    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace Allspark.Core.Common.Config
    {
        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
                    {
    
                    }
                }
    
            }
            /// <summary>
            /// 根据名称读取指定配置文件。若无法读取到数据,则使用defaultValue的值
            /// </summary>
            /// <typeparam name="T">节点的类型,可传对象</typeparam>
            /// <param name="name">配置文件节点名</param>
            /// <param name="defaultValue">默认值</param>
            /// <returns></returns>
            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;
            }
            /// <summary>
            /// 根据名称读取指定配置文件
            /// </summary>
            /// <typeparam name="T">节点的类型,可传对象</typeparam>
            /// <param name="name">配置文件节点名</param>
            /// <returns></returns>
            public static T Get<T>(string name)
            {
                return Get<T>(name, default);
            }
    
            public static string Set<T>(string key, T value)
            {
                string StrValue = JsonHelper.ObjectToJson(value);
                IEnumerable<IConfigurationProvider> configProviders = ConfigCache.ConfigRoot.Providers;
                foreach (IConfigurationProvider item in configProviders)
                {
                    if (item.TryGet(key, out string itemValue))
                    {
                        item.Set(key, StrValue);
                        return StrValue;
                    }
                }
                return "";
            }
    
        }
    }
    
    
  • 相关阅读:
    爬虫从入门到入狱
    4常用标准库之strconv
    3常用标准库之time
    5自定义errors
    Elasticsearch从入门到集群架构
    7常用标准库之Template
    8常用标准库之Http
    7常用标准库之IO操作文件写
    OpsAny 配置 ldap 同步微软 AD 活动目录用户
    MySQL进阶系列:多版本并发控制 MVCC
  • 原文地址:https://www.cnblogs.com/hanfan/p/10402120.html
Copyright © 2020-2023  润新知