dotnet core 3.0 PublishSingleFile can't find appsettings.json

11/14/2019
Back to List

Problem

When publishing a dotnet core 3.0 application with PublishSingleFile=true an exception is thrown on startup because it can't find appsettings.json

Unhandled exception. System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.

Solution

When publishing as a single file the application is extracted and run from a temporary directory that is separate from the application.exe you run.  To make it look for appsettings.json in the correct location you have to set the base path when building the configuration.

The following will return the correct base patch depending on whether you are running in development or production mode.

private static string GetBasePath()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;
if(isDevelopment)
{
return Directory.GetCurrentDirectory();
}
using var processModule = Process.GetCurrentProcess().MainModule;
return Path.GetDirectoryName(processModule?.FileName);
}

Then use GetBasePath() to set the base path before adding the json file

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(GetBasePath());
config.AddJsonFile("appsettings.json", optional: false);
})
.UseStartup<Startup>();
}

SuperChad
Gravatar About Sean Nelson
I like codes and stuff.

2 comments
Gravatar Lulu Paul - 3/10/2021 4:43:45 AM
Thanks for this solution. Worked like a charm!
Gravatar Justin - 3/23/2020 12:59:17 AM
Long time supporter, and thought I'd drop a comment. Your wordpress site is very sleek - hope you don't mind me asking what theme you're using? (and don't mind if I steal it? :P) I just launched my site --also built in wordpress like yours-- but the theme slows (!) the site down quite a bit. In case you have a minute, you can find it by searching for "royal cbd" on Google (would appreciate any feedback) - it's still in the works. Keep up the good work-- and hope you all take care of yourself during the coronavirus scare!