最近在開(kāi)發(fā)基于.NET Core的NuGet包,遇到一個(gè)問(wèn)題:
.NET Core中已經(jīng)沒(méi)有ConfigurationManager
類,在類庫(kù)中無(wú)法像.NET Framework那樣讀取App.config
或Web.config
(.NET Core中是appsetings.json)文件中的數(shù)據(jù)纲辽。
但,我們可以自己寫(xiě)少量代碼來(lái)實(shí)現(xiàn)在類庫(kù)中讀取配置文件信息。
思路:
先在當(dāng)前目錄下尋找appsettings.json
文件
- 若存在轧邪,則讀取改文件中的配置信息
- 不存在刽脖,則到根目錄中尋找
appsettings.json
文件
具體做法如下:
使用NuGet安裝
Microsoft.Extensions.Configuration.Json
包實(shí)現(xiàn)代碼
public static class ConfigHelper
{
private static IConfiguration _configuration;
static ConfigHelper()
{
//在當(dāng)前目錄或者根目錄中尋找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;
}
}
測(cè)試
在根目錄下或當(dāng)前目錄下添加appsetting.json
文件,并添加節(jié)點(diǎn):
{
"key": "value"
}
測(cè)試代碼如下:
public class ConfigHelperTest
{
[Fact]
public void GetSectionValueTest()
{
var value = ConfigHelper.GetSectionValue("key");
Assert.Equal(value, "value");
}
}
測(cè)試通過(guò):
測(cè)試通過(guò)
順道安利下一款用于.NET開(kāi)發(fā)的跨平臺(tái)IDE——Rider忌愚,以上代碼均在Rider中編寫(xiě)曲管。
這是NuGet包項(xiàng)目地址:https://github.com/CwjXFH/WJChiLibraries,希望大家多多指點(diǎn)硕糊。