I have a .Net core worker service, which I am running as a windows service. The service is using appsettings.json file for the config information. After installing the service using SC CREATE
command, the service was failing.
In the event viewer I found the error it cannot find the file C:\Windows\System32\appsettings.json
. My service files are placed in a different folder c:\Services\
, instead of looking at that location, the service is looking for a the file in System32 folder.
The configuration registration is as below.
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = configBuilder.Build();
services.AddSingleton(configuration);
How can I make the service to look at the local folder?
That's because the current directory is changed to C:\Windows\System32
at runtime. You could get a relative path by Assembly.GetExecutingAssembly()
. For example:
var configBuilder = new ConfigurationBuilder()
.SetBasePath( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location))
.AddJsonFile("appsettings.json");
var configuration = configBuilder.Build();