C# Set local folder for .net Core Windows Services

When developing .NET Core Worker Services, you can allow the service to run as Windows Service:

public static IHostBuilder CreateHostBuilder(string[] args)
{
  var host = Host.CreateDefaultBuilder(args);
  host.UseWindowsService();
  ...
  ...

The side effect is that the root folder changes from the local folder to the System32 folder, which means that any log files that you would expect to find in your local folder suddenly ends up in another folder.

The fix is easy, simple add the following to the main function of your application:

public static void Main(string[] args)
{
  Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
  CreateHostBuilder(args).Build().Run();
}

SetCurrentDirectory will then rebase the local folder to the base directory of your application, and your log files will be written to the local folder.

MORE TO READ:

 

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .NET Core, c# and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.