您的位置:首页 > 其它

.NET Core类库中读取配置文件

2018-03-07 14:59 591 查看
最近在开发基于.NET Core的NuGet包,遇到一个问题:
.NET Core中已经没有
ConfigurationManager
类,在类库中无法像.NET Framework那样读取
App.config
Web.config
(.NET Core中是appsetings.json)文件中的数据。

但,我们可以自己写少量代码来实现在类库中读取配置文件信息。

思路:

先在当前目录下寻找
appsettings.json
文件

若存在,则读取改文件中的配置信息

不存在,则到根目录中寻找
appsettings.json
文件

具体做法如下:

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


实现代码

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;
}
}


测试

在根目录下或当前目录下添加
appsetting.json
文件,并添加节点:

{
"key": "value"
}


测试代码如下:

public class ConfigHelperTest
{
[Fact]
public void GetSectionValueTest()
{
var value = ConfigHelper.GetSectionValue("key");
Assert.Equal(value, "value");
}
}


测试通过:



顺道安利下一款用于.NET开发的跨平台IDE——Rider,以上代码均在Rider中编写。

这是NuGet包项目地址:https://github.com/CwjXFH/WJChiLibraries,希望大家多多指点。

相关阅读

Configure an ASP.NET Core App

版权声明

本文为作者原创,版权归作者雪飞鸿所有。 转载必须保留文章的完整性,且在页面明显位置处标明原文链接

如有问题, 请发送邮件和作者联系。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: