如何在控制台应用程序中从config.json读取值 [英] How to read values from config.json in Console Application

查看:133
本文介绍了如何在控制台应用程序中从config.json读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚安装了ASP.NET 5,并在Visual Studio中创建了一个控制台应用程序.我已经在项目的根文件夹中添加了一个文件config.json.

I just installed ASP.NET 5 and created a Console Application in Visual Studio. I've added a file, config.json, to the root folder of the project.

它看起来像这样:

{
    "Data": {
        "TargetFolderLocations": {
            "TestFolder1": "Some path",
            "TestFolder2": "Another path"
        }
    }
}

我的Program.cs看起来像这样

My Program.cs looks like this

public void Main(string[] args)
{
    var configurationBuilder = new ConfigurationBuilder(Environment.CurrentDirectory)
    .AddJsonFile("config.json")
    .AddEnvironmentVariables();
    Configuration = configurationBuilder.Build();

    //Doesn't work...null all the time
    var test = Configuration.Get("Data:TargetFolderLocations");

    Console.ReadLine();
}

如何使用代码访问TargetFolderLocations密钥?

How can I access the TargetFolderLocations key with code?

推荐答案

具有如下类型:

public class FolderSettings
{
    public Dictionary<string, string> TargetFolderLocations { get; set; }
}

然后您可以使用ConfigurationBinder自动将配置节绑定到上述类型.示例:

You can then use the ConfigurationBinder to automatically bind configuration sections to types like above. Example:

var folderSettings = ConfigurationBinder.Bind<FolderSettings>(config.GetConfigurationSection("Data"));
var path = folderSettings.TargetFolderLocations["TestFolder1"];

这篇关于如何在控制台应用程序中从config.json读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆