.NET Core類庫中讀取配置文件


最近在開發基於.NET Core的NuGet包,遇到一個問題:
.NET Core中已經沒有ConfigurationManager類,在類庫中無法像.NET Framework那樣讀取App.configWeb.config(.NET Core中是appsetings.json)文件中的數據。

但,我們可以自己寫少量代碼來實現在類庫中讀取配置文件信息。

思路:

先在當前目錄下尋找appsettings.json文件

  • 若存在,則讀取改文件中的配置信息
  • 不存在,則到根目錄中尋找appsettings.json文件

具體做法如下:

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

  2. 實現代碼

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

版權聲明

本文為作者原創,版權歸作者雪飛鴻所有。 轉載必須保留文章的完整性,且在頁面明顯位置處標明原文鏈接

如有問題, 請發送郵件和作者聯系。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM