.NET Core讀取配置文件方式詳細(xì)總結(jié)
基于.NET Core的跨平臺開發(fā),配置文件與之前.NET Framework采用xml的config文件不同,目前主要是采用json文件鍵值對配置方式讀取。
參考網(wǎng)上相關(guān)資料總結(jié)如下:
一. 引入擴展 System.Configuration.ConfigurationManager
Nuget 下載擴展,Install-Package System.Configuration.ConfigurationManager

使用方式:添加配置文件App.config。讀取方式與原.NET Framework方式一致
優(yōu)點:兼容.NET Framework 原有配置方式
缺點:項目運行過程中若需修改App.config文件,對項目中輸出的內(nèi)容沒有絲毫影響,Debug發(fā)現(xiàn)獲取到的值的確沒有變化,需要重新編譯才生效。
二. 引入擴展 Microsoft.Extensions.Options.ConfigurationExtensions
Nuget 下載擴展,
Install-Package Microsoft.Extensions.Options.ConfigurationExtensions
Install-Package Microsoft.Extensions.Configuration.FileExtensions
Install-Package Microsoft.Extensions.Configuration.Json



使用方式:參考微軟官網(wǎng)
優(yōu)點:可以讀取application.json中的配置參數(shù),不再使用XML可以說很好的貼近Core的設(shè)計理念
缺點:運行時修改json文件讀取到的內(nèi)容不會改變,但是至少重啟項目可以修改,若要運行時候修改json文件監(jiān)聽實現(xiàn)監(jiān)聽變化。查看源碼,可以發(fā)現(xiàn) 雖然配置信息是通過AddSingleton注入的
但同時也注入了IOptionsChangeTokenSource ,故只需要在獲取配置信息時將IOptions<> 替換為 IOptionsMonitor<>(通過監(jiān)聽的Option來獲取信息),并通過 IOptionsMonitor<>.CurrentValue獲取即可實時獲取到最新的配置信息(存在修改監(jiān)聽)
另外就是,這個方法采用的是反序列化的原理,也就是必須有一個跟配置文件對應(yīng)的實體類才可以,這個感覺比較雞肋,放棄。
三. 自定義擴展方法,這個實現(xiàn)自己寫,原理是監(jiān)聽文件是否變更,來刷新Configuration 配置實現(xiàn)。
參考園友一個實現(xiàn),具體需要是否有效,要花時間實踐一下,原鏈接地址,代碼如下:
復(fù)制代碼
public class ConfigurationManager
{
/// <summary>
/// 配置內(nèi)容
/// </summary>
private static NameValueCollection _configurationCollection = new NameValueCollection();
/// <summary>
/// 配置監(jiān)聽響應(yīng)鏈堆棧
/// </summary>
private static Stack<KeyValuePair<string, FileSystemWatcher>> FileListeners = new Stack<KeyValuePair<string, FileSystemWatcher>>();
/// <summary>
/// 默認(rèn)路徑
/// </summary>
private static string _defaultPath = Directory.GetCurrentDirectory() + "\\appsettings.json";
/// <summary>
/// 最終配置文件路徑
/// </summary>
private static string _configPath = null;
/// <summary>
/// 配置節(jié)點關(guān)鍵字
/// </summary>
private static string _configSection = "AppSettings";
/// <summary>
/// 配置外連接的后綴
/// </summary>
private static string _configUrlPostfix = "Url";
/// <summary>
/// 最終修改時間戳
/// </summary>
private static long _timeStamp = 0L;
/// <summary>
/// 配置外鏈關(guān)鍵詞,例如: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>
/// 讀取配置文件內(nèi)容
/// </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>
/// 添加監(jiān)聽樹節(jié)點
/// </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>
/// 手動刷新配置,修改配置后,請手動調(diào)用此方法,以便更新配置參數(shù)
/// </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; }
//釋放掉全部監(jiān)聽響應(yīng)鏈
while (FileListeners.Count > 0)
FileListeners.Pop().Value.Dispose();
ConfigFinder(_defaultPath);
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
.Net?Core應(yīng)用增強型跨平臺串口類庫CustomSerialPort()詳解
本文詳細(xì)講解了.Net?Core應(yīng)用增強型跨平臺串口類庫CustomSerialPort(),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01
.NET Windbg分析某婦產(chǎn)醫(yī)院WPF內(nèi)存溢出
這篇文章主要為大家介紹了.NET Windbg分析某婦產(chǎn)醫(yī)院WPF內(nèi)存溢出,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
基于MVC5中的Model層開發(fā)數(shù)據(jù)注解
下面小編就為大家分享一篇基于MVC5中的Model層開發(fā)數(shù)據(jù)注解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
asp.net中使用cookie與md5加密實現(xiàn)記住密碼功能的實現(xiàn)代碼
雖然.net內(nèi)置了登陸控件,有記住密碼的功能,但還是想自己實踐一下,以下代碼主要應(yīng)用了COOKIE,包括安全加密的過程等2013-02-02
asp.net 分頁sql語句(結(jié)合aspnetpager)
一直用的是存儲過程分頁,小項目一般不寫存儲過程,就需要直接寫分頁sql語句。2009-01-01

