基于.NET Core的跨平台开发,配置文件与之前.NET Framework采用xml的config文件不同,目前主要是采用json文件键值对配置方式读取。

参考网上相关资料总结如下:

一、引入扩展 System.Configuration.ConfigurationManager

Nuget 下载扩展,Install-Package System.Configuration.ConfigurationManager

使用方式:添加配置文件App.config。读取方式与原.NET Framework方式一致

优点:兼容.NET Framework 原有配置方式

缺点:项目运行过程中若需修改App.config文件,对项目中输出的内容没有丝毫影响,Debug发现获取到的值的确没有变化,需要重新编译才生效。

二、引入扩展 Microsoft.Extensions.Options.ConfigurationExtensions

Nuget 下载扩展,

Install-Package Microsoft.Extensions.Options.ConfigurationExtensions

Install-Package Microsoft.Extensions.Configuration.FileExtensions

Install-Package Microsoft.Extensions.Configuration.Json

使用方式:参考微软官网:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/index?view=aspnetcore-2.1&tabs=basicconfiguration

优点:可以读取application.json中的配置参数,不再使用XML可以说很好的贴近Core的设计理念

缺点:运行时修改json文件读取到的内容不会改变,但是至少重启项目可以修改,若要运行时候修改json文件监听实现监听变化。查看源码,可以发现 虽然配置信息是通过AddSingleton注入的
但同时也注入了IOptionsChangeTokenSource ,故只需要在获取配置信息时将IOptions<> 替换为 IOptionsMonitor<>(通过监听的Option来获取信息),并通过 IOptionsMonitor<>.CurrentValue获取即可实时获取到最新的配置信息(存在修改监听)

另外就是,这个方法采用的是反序列化的原理,也就是必须有一个跟配置文件对应的实体类才可以,这个感觉比较鸡肋,放弃。

三、自定义扩展方法,这个实现自己写,原理是监听文件是否变更,来刷新Configuration 配置实现。

参考园友一个实现,具体需要是否有效,要花时间实践一下,原链接地址:http://www.cnblogs.com/kasimlz/p/7515810.html,代码如下:

public class ConfigurationManager
{
/// <summary>
/// 配置内容
/// </summary>
private static NameValueCollection _configurationCollection = new NameValueCollection(); /// <summary>
/// 配置监听响应链堆栈
/// </summary>
private static Stack<KeyValuePair<string, FileSystemWatcher>> FileListeners = new Stack<KeyValuePair<string, FileSystemWatcher>>(); /// <summary>
/// 默认路径
/// </summary>
private static string _defaultPath = Directory.GetCurrentDirectory() + "\\appsettings.json"; /// <summary>
/// 最终配置文件路径
/// </summary>
private static string _configPath = null; /// <summary>
/// 配置节点关键字
/// </summary>
private static string _configSection = "AppSettings"; /// <summary>
/// 配置外连接的后缀
/// </summary>
private static string _configUrlPostfix = "Url"; /// <summary>
/// 最终修改时间戳
/// </summary>
private static long _timeStamp = 0L; /// <summary>
/// 配置外链关键词,例如:AppSettings.Url
/// </summary>
private static string _configUrlSection { get { return _configSection + "." + _configUrlPostfix; } } static ConfigurationManager()
{
ConfigFinder(_defaultPath);
} /// <summary>
/// 确定配置文件路径
/// </summary>
private static void ConfigFinder(string Path)
{
_configPath = Path;
JObject config_json = new JObject();
while (config_json != null)
{
config_json = null;
FileInfo config_info = new FileInfo(_configPath);
if (!config_info.Exists) break; FileListeners.Push(CreateListener(config_info));
config_json = LoadJsonFile(_configPath);
if (config_json[_configUrlSection] != null)
_configPath = config_json[_configUrlSection].ToString();
else break;
} if (config_json == null || config_json[_configSection] == null) return; LoadConfiguration();
} /// <summary>
/// 读取配置文件内容
/// </summary>
private static void LoadConfiguration()
{
FileInfo config = new FileInfo(_configPath);
var configColltion = new NameValueCollection();
JObject config_object = LoadJsonFile(_configPath);
if (config_object == null || !(config_object is JObject)) return; if (config_object[_configSection]!=null)
{
foreach (JProperty prop in config_object[_configSection])
{
configColltion[prop.Name] = prop.Value.ToString();
}
} _configurationCollection = configColltion;
} /// <summary>
/// 解析Json文件
/// </summary>
/// <param name="FilePath">文件路径</param>
/// <returns></returns>
private static JObject LoadJsonFile(string FilePath)
{
JObject config_object = null;
try
{
StreamReader sr = new StreamReader(FilePath, Encoding.Default);
config_object = JObject.Parse(sr.ReadToEnd());
sr.Close();
}
catch { }
return config_object;
} /// <summary>
/// 添加监听树节点
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
private static KeyValuePair<string, FileSystemWatcher> CreateListener(FileInfo info)
{ FileSystemWatcher watcher = new FileSystemWatcher();
watcher.BeginInit();
watcher.Path = info.DirectoryName;
watcher.Filter = info.Name;
watcher.IncludeSubdirectories = false;
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size;
watcher.Changed += new FileSystemEventHandler(ConfigChangeListener);
watcher.EndInit(); return new KeyValuePair<string, FileSystemWatcher>(info.FullName, watcher); } private static void ConfigChangeListener(object sender, FileSystemEventArgs e)
{
long time = TimeStamp();
lock (FileListeners)
{
if (time > _timeStamp)
{
_timeStamp = time;
if (e.FullPath != _configPath || e.FullPath == _defaultPath)
{
while (FileListeners.Count > )
{
var listener = FileListeners.Pop();
listener.Value.Dispose();
if (listener.Key == e.FullPath) break;
}
ConfigFinder(e.FullPath);
}
else
{
LoadConfiguration();
}
}
}
} private static long TimeStamp()
{
return (long)((DateTime.UtcNow - new DateTime(, , , , , , DateTimeKind.Utc)).TotalMilliseconds * );
} private static string c_configSection = null;
public static string ConfigSection
{
get { return _configSection; }
set { c_configSection = value; }
} private static string c_configUrlPostfix = null;
public static string ConfigUrlPostfix
{
get { return _configUrlPostfix; }
set { c_configUrlPostfix = value; }
} private static string c_defaultPath = null;
public static string DefaultPath
{
get { return _defaultPath; }
set { c_defaultPath = value; }
} public static NameValueCollection AppSettings
{
get { return _configurationCollection; }
} /// <summary>
/// 手动刷新配置,修改配置后,请手动调用此方法,以便更新配置参数
/// </summary>
public static void RefreshConfiguration()
{
lock (FileListeners)
{
//修改配置
if (c_configSection != null) { _configSection = c_configSection; c_configSection = null; }
if (c_configUrlPostfix != null) { _configUrlPostfix = c_configUrlPostfix; c_configUrlPostfix = null; }
if (c_defaultPath != null) { _defaultPath = c_defaultPath; c_defaultPath = null; }
//释放掉全部监听响应链
while (FileListeners.Count > )
FileListeners.Pop().Value.Dispose();
ConfigFinder(_defaultPath);
}
} }

.NET Core 读取配置文件方式总结的更多相关文章

  1. Core 读取配置文件

    新建控制台 static void Main(string[] args) { Console.WriteLine("Hello World!"); //获取应用程序的当前工作目录 ...

  2. .net core 读取配置文件的值

    .net core中的配置文件可以存一些自定义的值,我们需要去读取 在配置中添加json: "name": "sealee", "Connection ...

  3. ASP .NET CORE 读取配置文件的方法

    老式的config文件在ASP.net core2.0中变成了appsettings.json,如果想要读取自定义配置,可以写如下代码 { "Logging": { "I ...

  4. .net core 读取配置文件

    /// <summary> /// 读取配置信息 /// </summary> public class Zconfig { #region 读取配置信息 /// <su ...

  5. .Net Core 读取配置文件 appsettings.json

    1. 首先些一个类 public class MySettings { public string P1 { get; set; } public string P2 { get; set; } } ...

  6. Asp.net Core 和类库读取配置文件信息

    Asp.net Core 和类库读取配置文件信息 看干货请移步至.net core 读取配置文件公共类 首先开一个脑洞,Asp.net core 被使用这么长时间了,但是关于配置文件(json)的读取 ...

  7. .net core 学习 读取配置文件

    在空项目中是没有配置文件的,首先要新建一个,配置文件内容如下,下面来读取各个内容 { "ConnectionStrings": { "DefaultConnection& ...

  8. 【转】spring boot mybatis 读取配置文件

    spring boot mybatis 配置整理 一.加载mybatis的配置 1.手写配置,写死在代码里 import java.io.IOException; import java.util.P ...

  9. .net core 读取appsettings.json乱码

    .net core 读取配置文件乱码:vs2019读取appsettings.json乱码问题; .net core 读取appsettings.json乱码问题;用notepad++或者其他编辑器打 ...

随机推荐

  1. C++ STL vector的学习

    vector就是一个不定长数组,vector是动态数组,随着元素的加入,它的内部机制会自行扩充空间以容纳新元素,使用vector之前,必须包含相应的头文件和命名空间. #include <vec ...

  2. 【Offer】[19] 【字符串匹配】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 请实现一个函数用来匹配包括'.'和'*'的正则表达式. 模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含 ...

  3. java中最容易犯错的特殊字符

    问题背景 能准确说出下面的java 执行完毕后会打印出什么? System.out.println( String.class.getName()+ ".class"); Syst ...

  4. redis之pipeline使用

    redis之pipeline 我们要完成一个业务,可能会对redis做连续的多个操作,这有很多个步骤是需要依次连续执行的.这样的场景,网络传输的耗时将是限制redis处理量的主要瓶颈. 那么此时就可以 ...

  5. ASP.NET Core 2.2 : 二十一. 内容协商与自定义IActionResult和格式化类

    上一章的结尾留下了一个问题:同样是ObjectResult,在执行的时候又是如何被转换成string和JSON两种格式的呢? 本章来解答这个问题,这里涉及到一个名词:“内容协商”.除了这个,本章将通过 ...

  6. 一次写文,多平台直接粘贴&打造最流畅的写作流程

    文字爱好者的痛点 这一段可以跳过,解决办法在后面.因为大家既然痛过,也就懂了. 对于很多文字爱好者来说,都希望写一篇文章后,可以实现多平台发布. 国内的很多平台都开始支持 Markdown,除了微信公 ...

  7. style属性css与javascript对照表

    有时候会用javascript来控制标签的style,但js的style属性写法跟css有点不一样,通常是一个单词的写法不变,单词-单词属性会去掉“-”,再把第二个单词的首字母大写,估计是为了与减法运 ...

  8. 一文轻松搞懂Vuex

    概念: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式(官网地址:https://vuex.vuejs.org/zh/).它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状 ...

  9. ADC0832

    #include <reg51.h> #include "ADC0832.c" code uchar seven_seg[]={0xc0, 0xf9, 0xa4, 0x ...

  10. 同步FIFO design and IP level verification

    一.前言 应聘IC前端相关岗位时,FIFO是最常考也是最基本的题目.FIFO经常用于数据缓存.位宽转换.异步时钟域处理.随着芯片规模的快速增长,灵活的system verilog成为设计/验证人员的基 ...