干货:.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
测试浏览效果:http://127.0.0.1:1994/home/TestConfig
帮助到你的话请点个推荐,谢谢。
分类:
开发日志
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构