.NET CORE类库读取配置文件

原文出自https://www.cnblogs.com/Cwj-XFH/p/8522450.html 感谢提供。

1.使用NuGet安装Microsoft.Extensions.Configuration.Json

2.创建一个ConfigHelper.cs文件。代码如下

 public static class ConfigHelper
    {
        private static IConfiguration _configuration;

        static ConfigHelper()
        {
            //在当前目录或者根目录中寻找appsettings.json文件
            var fileName = "appsettings.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;
        }
    }
ConfigHelper

3.在appsettings.json中加入测试的字符串键值对

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "connStr": "User id=sa;Password=Jack@2019;Database=JackDB;Server=127.0.0.1;Connect Timeout=50;Max Pool size=200;Min pool Size=5"
}
 
appsettings.json

4.获取配置文件的值

 string connStr = ConfigHelper.GetSectionValue("connStr");
GetValue

完成,亲测可用。

猜你喜欢

转载自www.cnblogs.com/cdjbolg/p/12162731.html