看好多人不懂在.NET CORE中如何讀取組態檔,我這里分了兩篇,上一篇介紹了怎樣通過appsettings.json配置讀取檔案資訊,這一篇教大家自定義組態檔:
1.在專案下創建組態檔

{ "FileMap": { "ImgPath": "D:\\myfile\\misc\\NPSPower\\TemplateCore\\TemplateCore\\wwwroot\\UpImg\\", "ImgWeb": "http://127.0.0.1:1994/UpImg/", "FilePath": "D:\\myfile\\misc\\NPSPower\\TemplateCore\\TemplateCore\\wwwroot\\UpFile\\", "FileWeb": "http://127.0.0.1:1994/UpFile/", "VideoPath": "D:\\myfile\\misc\\NPSPower\\TemplateCore\\TemplateCore\\wwwroot\\UpVideo\\", "VideoWeb": "http://127.0.0.1:1994/UpVideo/", "Web": "http://127.0.0.1:1994/" } }
2.參考類別庫Microsoft.Extensions.Configuration.Json并創建組態檔操作類ConfigHelper.cs
Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0

using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Common { public class ConfigHelper { private static IConfiguration _configuration; static ConfigHelper() { //在當前目錄或者根目錄中尋找檔案 var fileName = "Config/ManagerConfig.json"; var directory = AppContext.BaseDirectory; directory = directory.Replace("\\", "/"); var filePath = $"{directory}/{fileName}"; if (!File.Exists(filePath)) { var length = directory.IndexOf("/bin"); filePath = $"{directory.Substring(0, length)}/{fileName}"; } var builder = new ConfigurationBuilder() .AddJsonFile(filePath, false, true); _configuration = builder.Build(); } public static string GetSectionValue(string key) { return _configuration.GetSection(key).Value; } } }
3.在專案中讀取組態檔
string ImgPath = ConfigHelper.GetSectionValue("FileMap:ImgPath"); return ImgPath;

開源地址:https://github.com/jiyuwu/TemplateCore
測驗瀏覽效果:http://127.0.0.1:1994/home/TestConfig

幫助到你的話請點個推薦,謝謝,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/112669.html
標籤:C#
