11

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?

3
  • Is it Data.TargetFolderLocations? Commented Aug 7, 2015 at 20:19
  • Doesn't work with .TargetFolderLocations either unfortunately... Commented Aug 7, 2015 at 20:21
  • I've managed to solve it, please see my answer :) Commented Aug 7, 2015 at 21:07

4 Answers 4

7

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"];
Sign up to request clarification or add additional context in comments.

1 Comment

this is really clean, I had it bound to types previously but I think the syntax changed and I couldn't find any documentation...will try this out and accept it as correct answer if it works!
4

You can use JavascriptSerializer (namespace: System.Web.Extension) to parse json into dictionary and find any value based on its key from json. You code would become:

 string json = System.IO.File.ReadAllText("PathToJsonFile");
 JavaScriptSerializer serializer = new JavaScriptSerializer();
 Dictionary<string, object> dic = serializer.Deserialize<Dictionary<string, object>>(json);

If you iterate over the dictionary, you can see all the keys and get their values using dic.

* Just an alternate solution *

Comments

4

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

1 Comment

Thanks JOSEFtw. You need to initialise your "Paths" dictionary variable else you will get a NULL exception.
3

The way you've worded your question, your config.json file is at the root of the project, but you're looking in the executable directory at runtime. Assuming you're doing this from Visual Studio, and assuming you're not copying the config file in at build time, Environment.CurrentDirectory is probably bin\Debug, and the file is not there.

You can set the properties of config.json to Copy always from Solution Explorer, to ensure the file gets there.

2 Comments

This is no longer the case. In VS 2015 with .NET Core 1.0 tools installed you no longer have that option. Instead, add this inside "buildOptions" in project.json: "copyToOutput": [ "config.json" ]
@ScottRFrost thank you. Finally got my console application running.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.