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

true );_configuration = builder.Build();} public static str

2024-03-31 Web开发

原文出自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.WordStr("\\", "/"); 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;[email protected];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

完成,,亲测可用。

.NET CORE类库读取配置文件

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