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?
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"];
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With