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 Fafcryday - 11/15/2024 10:01:40 PM
Caution is advised when alpha adrenergic antagonists, including UROXATRAL, are co administered with PDE5 inhibitors <a href=https://fastpriligy.top/>priligy pill</a> Melatonin plays a significant role in human development in utero where the hormone exhibits effects on placenta function and early nervous system development
Gravatar Lulu Paul - 3/10/2021 4:43:45 AM
Thanks for this solution. Worked like a charm!