Set Local Folder for .NET Core in C#
By FoxLearn 1/10/2025 8:15:16 AM 41
public static IHostBuilder CreateHostBuilder(string[] args) { var host = Host.CreateDefaultBuilder(args); host.UseWindowsService(); // ... }
However, one common issue that arises when a .NET Core Worker Service is hosted as a Windows Service is a change in the root directory.
By default, the working directory of a Windows Service is set to System32
, which can cause confusion and issues with file paths.
For example, any log files you expect to be written to your local folder will instead be written to the System32
folder.
Set the Local Folder to the Application’s Base Directory
The fix for this problem, you can explicitly set the current directory of the application to its base directory using the Directory.SetCurrentDirectory
method.
This ensures that the working directory remains within your application’s directory, allowing logs and other file-based operations to occur in the correct folder.
Add the following code to the Main
function of your application:
public static void Main(string[] args) { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); CreateHostBuilder(args).Build().Run(); }
The SetCurrentDirectory
method re-bases the local folder to the base directory of your application. This ensures that any files, such as logs, that are created during the service's operation are written to the correct local folder, rather than the default System32
folder.
- How to Convert string to JSON in C#
- How to take a screenshot with Selenium WebDriver
- Sending JSON in .NET Core
- Writing Files Asynchronously with Multiple Threads in .NET Core
- Manipulating XML Google Merchant Data with C# and LINQ
- How to Remove Duplicates from a List with LINQ in C#
- HttpClient Follow 302 Redirects in .NET Core
- Ignoring Namespaces in XML when Deserializing in C#