Reputation: 2403
Trying to convert Dotnet Core 3.1 to Dotnet6 CONSOLE applications and keep getting
"The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was 'C:\Windows\system32\appsettings.json'."
error message. The thing is, the appsettings.json file IS copied to the publish folder, but I get the error in the Application log and nothing happens.
There are other posts here, but I can't find one specific to DotNet6 (they got rid of startup.cs and are doing things radically different) AND specific to console applications.
I have the appsettings.json Build Action set to Content (or nothing) and set to Copy To Output Directory to Copy Always. The file is absolutely present in the publish folder (and on the server it's running on).
static async Task Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) //doesn't work on publish (appsettings.json set to "copy always" - no joy) - thing is that is DOES copy it over, but the program can't find it!
.AddJsonFile("appsettings.json")
.Build();
I'm presuming the .SetBasePath part is incorrect as in other solutions here, but can't apply dotnet5 solutions to this problem. I know I'm doing something wrong, but can't find a solution for DotNet6 console app configuration. Some suggest to create the project in DotNet5, then convert to DotNet6, but that really doesn't fix the problem (too hacky) nor do I learn the new/correct way to configure it. Any ideas?
Upvotes: 3
Views: 5085
Reputation: 2403
Ok - found a way this works now. Still looks like a kludge, but it works and I'm happy ... for now.
var configuration = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
.AddJsonFile("appsettings.json")
.Build();
Surely, there is a built in function for this, but I can't seem to find an example that works once published.
********** UPDATE *********************
This works perfectly:
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
Upvotes: 7
Reputation: 106
Environment.CurrentDirectory
should work.
You can check the documentation here.
The code snippet looks like this
var configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
EDIT: This also works for published apps
EDIT 2: I found a more elegant solution for the scenario described here. Please check my other answer.
Upvotes: 0