I follow the Microsoft guide to build a Windows service.
The appSettings.json
file is read when running from the Visual Studio or command line, but when the service DLL is executed from the Service Manager, it fails.
All variables populated from config remain empty remain empty.
The problem is that Windows Service Manager set the default directory to c:\windows\system32
.
How to read from installation path?
At service startup, set the working path to the installation path this way:
//program.cs
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(conf =>
{
conf.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
})
...
This modification ensures that the working path is set to the installation path, allowing proper access to configuration files when the service is executed from the Service Manager.