Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read values from config.json in Console Application

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.

It looks like this:

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

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

How can I access the TargetFolderLocations key with code?

like image 611
JOSEFtw Avatar asked Aug 07 '15 20:08

JOSEFtw


Video Answer


2 Answers

Have a type like the following:

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

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"];
like image 94
Kiran Avatar answered Nov 10 '22 20:11

Kiran


I've managed to solve it like this:

public class Program
{
    public IConfiguration Configuration { get; set; }
    public Dictionary<string,string> Paths { get; set; } 
    public Program(IApplicationEnvironment app,
           IRuntimeEnvironment runtime,
           IRuntimeOptions options)
    {
        Paths = new Dictionary<string, string>();
        Configuration = new ConfigurationBuilder()
            .AddJsonFile(Path.Combine(app.ApplicationBasePath, "config.json"))
            .AddEnvironmentVariables()
            .Build();
    }

    public void Main(string[] args)
    {
        var pathKeys = Configuration.GetConfigurationSections("TargetFolderLocations");
        foreach (var pathItem in pathKeys)
        {
            var tmp = Configuration.Get($"TargetFolderLocations:{pathItem.Key}");
            Paths.Add(pathItem.Key, tmp);
        }

        return;
    }
like image 22
JOSEFtw Avatar answered Nov 10 '22 19:11

JOSEFtw