看好多人不懂在.NET CORE中如何讀取配置文件,我這裏分了兩篇,上一篇介紹了怎樣經過appsettings.json配置讀取文件信息。這一篇教你們自定義配置文件:html
1.在項目下建立配置文件git
{ "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.csgithub
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.在項目中讀取配置文件json
string ImgPath = ConfigHelper.GetSectionValue("FileMap:ImgPath"); return ImgPath;
開源地址:https://github.com/jiyuwu/TemplateCoreapp
測試瀏覽效果:http://127.0.0.1:1994/home/TestConfigide
幫助到你的話請點個推薦,謝謝。測試