当前位置:首页 > Web开发 > 正文

干货:.net core实现读取自定义配置文件,有源代码哦

2024-03-31 Web开发

标签:

原文:干货:.net core实现读取自定义配置文件,有源代码哦

看好多人不懂在.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

测试浏览效果::1994/home/TestConfig

技术图片

 帮助到你的话请点个推荐,谢谢。

干货:.net core实现读取自定义配置文件,,有源代码哦

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/42254.html