最近在開發基於.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,希望大家多多指點。