Reputation: 7959
While building a .net console app which uses the new ConfigurationBuilder
implementation for what used to be appSettings
, I've run into a problem.
I have the following code:
public static void Main(string[] args)
{
try
{
var builder = new ConfigurationBuilder().AddJsonFile("config.json");
var config = builder.Build();
if (config["Azure"] != null)
{
;
}
}
catch (System.IO.FileNotFoundException exception)
{
...
}
}
The config.json
file is in the same directory and looks like this:
{
"Azure": {
"Storage": {
"ConnectionString": "...",
"ContainerName": "..."
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "..."
}
},
"Logging": {
"RecordProgress": "..."
}
}
But the config
object contains no keys.
I read somewhere that if the file path passed to AddJsonFile
can't be found then it throws a FileNotFoundException
but in my code that exception is never thrown.
So presuming the config.json file can be found, why are the settings not being loaded?
Upvotes: 2
Views: 2260
Reputation:
I encountered the same problem.
config.json was in the correct directory and it was still not found.
The solution: config.json contained a typo that broke the json syntax. After fixing the json syntax/format in config.json everything worked.
Upvotes: 0
Reputation: 13183
My original answer was off the mark. Here's an updated version. This is based on the recently released RC2.
The current runtime will throw FileNotFoundException
if the config file isn't found. The AddJsonFile()
extension method takes an optional parameter called optional
that, if true, will cause the method not to throw.
I added config.json
and it doesn't get copied to the bin directory, so I had to specify the location using the SetBasePath()
extension method. This is what the Web project templates do in Startup, using IHostingEnvironment.ContentRootPath
. In console apps, you can use Directory.GetCurrentDirectory()
.
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json");
var config = builder.Build();
Finally, the config["Key"]
indexer didn't work for me. Instead, I had to use the GetSection()
extension method. So your example config file above might be accessed with:
// var result = config["Logging"];
var section = config.GetSection("Logging");
var result = section["RecordProgress"];
I left the old answer for the time being.
Old answer: I found a possible solution here: https://github.com/aspnet/Mvc/issues/4481.
Quoting from the issue.
Thanks for the repro project. Looks like you need to update the project.json file to have the "content" node and have Config.json specified here.
Example: https://github.com/aspnet/MusicStore/blob/dev/src/MusicStore/project.json#L22
It appears that a new content element may be required in your project.json
.
...
"content": [
"Areas",
"Views",
"wwwroot",
"config.json",
"web.config"
],
...
Upvotes: 7