干货:.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

 

 

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

posted @ 2019-11-01 12:26  殷慈航  阅读(2038)  评论(2编辑  收藏  举报