.NET Core读取配置文件方式详细总结
 更新时间:2018年08月06日 16:31:48   作者:戈多编程  

这篇文章主要为大家详细总结了.NET Core读取配置文件方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

基于.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

使用方式:参考微软官网
优点:可以读取application.json中的配置参数,不再使用XML可以说很好的贴近Core的设计理念
缺点:运行时修改json文件读取到的内容不会改变,但是至少重启项目可以修改,若要运行时候修改json文件监听实现监听变化。查看源码,可以发现 虽然配置信息是通过AddSingleton注入的
但同时也注入了IOptionsChangeTokenSource ,故只需要在获取配置信息时将IOptions<> 替换为 IOptionsMonitor<>(通过监听的Option来获取信息),并通过 IOptionsMonitor<>.CurrentValue获取即可实时获取到最新的配置信息(存在修改监听)
另外就是,这个方法采用的是反序列化的原理,也就是必须有一个跟配置文件对应的实体类才可以,这个感觉比较鸡肋,放弃。
三. 自定义扩展方法,这个实现自己写,原理是监听文件是否变更,来刷新Configuration 配置实现。
参考园友一个实现,具体需要是否有效,要花时间实践一下,原链接地址,代码如下:
复制代码

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 > 0)
{
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(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds * 100);
}

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 > 0)
FileListeners.Pop().Value.Dispose();
ConfigFinder(_defaultPath);
}
}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

您可能感兴趣的文章:ASP.NET core Web中使用appsettings.json配置文件的方法.NET Core简单读取json配置文件.NET Core 2.0迁移小技巧之web.config 配置文件示例详解实现core文件自动生成配置文件的方法.NET Core2.1如何获取自定义配置文件信息详解如何在ASP.NET Core类库项目中读取配置文件详解Asp.net Core与类库读取配置文件信息的方法.Net Core读取Json配置文件的实现示例asp.net core配置文件加载过程的深入了解ASP.NET Core中修改配置文件后自动加载新配置的方法详解

.NET
Core
读取配置

相关文章
Global.asax取物理路径/取绝对路径具体方法本文章来给大家简单介绍利用Global.asax取物理路径和取绝对路径代码,有需要了解的朋友可参考参考 2013-08-08
.NET CORE中比较两个文件内容是否相同的最快方法这篇文章主要给大家介绍了关于.NET CORE中比较两个文件内容是否相同的最快方法,文中通过示例代码介绍的非常详细,对大家学习或者使用.NET CORE具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
2019-06-06
ASP.NET中GridView、DataList、DataGrid三个数据控件foreach遍历这篇文章主要介绍了ASP.NET中GridView、DataList、DataGrid三个数据控件foreach遍历用法,结合实例形式分析了GridView、DataList、DataGrid使用foreach及for语句进行数据遍历的具体使用方法,需要的朋友可以参考下 2016-08-08
ASP.Net MVC+Data Table实现分页+排序功能的方法这篇文章主要介绍了ASP.Net MVC+Data Table实现分页+排序功能的方法,结合实例形式分析了asp.net基于mvc架构实现的数据查询、排序、分页显示等相关操作技巧,需要的朋友可以参考下 2017-06-06
asp.net 点缩略图弹出随图片大小自动调整的页面程序用asp.net编写,功能主要是,点pic_small.Aspx页面的缩略图后弹出pic_all.aspx页面,pic_all.aspx页面的大小要根据图片大小自动调整 2009-06-06
从ASP.NET得到Microsoft Word文档的代码这篇文章是应在一个ASP.NET项目中建立Microsoft Word文档的需要而写的。本文描述了怎样使用ASP.NET来创建和修改Microsoft Word文档。 2011-06-06
asp.net中提示该行已属于另一个表的解决方法从一个TABLE中取一行放到另一个TABLE里报错: 该行已经属于另一个表。用下面来个方法就OK了,需要的朋友可以参考下 2013-09-09
.NET Core如何进行请求转发的实现这篇文章主要介绍了.NET Core如何进行请求转发的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 2020-11-11
asp.net core集成MongoDB的完整步骤前两天在学习MongoDB相关的知识,做了个小Demo,下面这篇文章主要给大家介绍了关于asp.net core集成MongoDB的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下 2018-10-10
数据库SqlParameter 的插入操作,防止sql注入的实现代码今天学习了一下SqlParameter的用法,原来这么写是为了防止sql注入,破坏数据库的。并自己动手连接了数据库。 2013-04-04

最新评论

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。