A .NET 10 worker running as a Windows Service loads appsettings.json, yet File.ReadAllText("tariffs.csv") looks in C:\Windows\system32; why, and how do you fix it?
answer
- two directories, not one
- the service's current directory
- content root falls back to the base directory
- relative paths ignore the content root
- ContentRootPath or --contentRoot
basics
~20 sWindows Services start with C:\Windows\system32 as current directory. The generic host detects that and uses AppContext.BaseDirectory as content root, so appsettings.json loads, but File APIs still resolve relative paths against the current directory. Build paths from IHostEnvironment.ContentRootPath.
solid answer
~40 sA process started by the Service Control Manager gets `C:\Windows\system32` as its current directory. The default builders take the current directory as the content root, except on Windows when it equals `Environment.SystemDirectory`; then `ContentRootPath` falls back to `AppContext.BaseDirectory`, the folder with the binaries. That is why `appsettings.json` loads. `File.ReadAllText("tariffs.csv")` knows nothing about the host: relative paths resolve against `Environment.CurrentDirectory`, which is still system32. Fix it by building paths from `IHostEnvironment.ContentRootPath` (or `ContentRootFileProvider`), or from `AppContext.BaseDirectory` for files shipped with the binaries, and never set the content root to `Directory.GetCurrentDirectory()`, which brings system32 back and makes the optional JSON files vanish silently. If data lives elsewhere, pass `--contentRoot` in the service's binary path. `AddWindowsService()` changes the lifetime and adds Event Log logging; it does not set any directory.
code
csharp · 9 linesHostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
string contentRoot = builder.Environment.ContentRootPath;
string tariffs = Path.Combine(contentRoot, "tariffs.csv"); // not just "tariffs.csv"
Console.WriteLine($"Current directory: {Environment.CurrentDirectory}");
Console.WriteLine($"Content root: {contentRoot}");
Console.WriteLine($"Base directory: {AppContext.BaseDirectory}");
Console.WriteLine($"Tariff file: {tariffs}");go deeper
Know that a Windows Service does not start in its install folder and that file paths should be built from a known directory, not left relative.
Separate the current directory, the host's content root and AppContext.BaseDirectory, and say which one each API uses.
Diagnose from the symptom: configuration loads because of the host's system32 fallback, while BCL file calls still use the current directory; fix with ContentRootPath or --contentRoot.
Set a rule that services never use relative paths and that every deployable logs its content root at start-up, so path bugs surface in the first log line.
## Two directories, not one A .NET worker has three paths that are easy to conflate: | Path | Who sets it | Who uses it | |---|---|---| | `Environment.CurrentDirectory` | whoever starts the process: a shell, `dotnet run`, the Service Control Manager | every relative path given to `File`, `FileStream`, `Path.GetFullPath`, `Directory` | | `IHostEnvironment.ContentRootPath` | the generic host, from the `contentRoot` host setting | the host's JSON configuration files and `ContentRootFileProvider` | | `AppContext.BaseDirectory` | the runtime: the folder holding the app's binaries | the fallback content root; a hand-built `ConfigurationBuilder` | From a terminal in the app folder all three are the same, so code that mixes them works on a developer machine. Under the **Service Control Manager**, service processes start with `C:\Windows\system32` as the current directory, and the three split apart. ## How the host picks the content root The default builders in `Microsoft.Extensions.Hosting` (both `Host.CreateApplicationBuilder` and `Host.CreateDefaultBuilder`) follow these steps: 1. If `contentRoot` was set (by `HostApplicationBuilderSettings.ContentRootPath`, a `DOTNET_CONTENTROOT` variable or a `--contentRoot` argument), use it. 2. Otherwise read `Environment.CurrentDirectory`. On Windows, if it equals `Environment.SystemDirectory`, deliberately leave the setting empty; the source comment names Windows Services and MSIX installers as the reason. 3. An empty content root resolves to `AppContext.BaseDirectory`. So the host itself is fine: `appsettings.json` next to the executable is found and the log line "Content root path:" shows the install folder. ## Why the CSV goes missing `File.ReadAllText("tariffs.csv")` is a BCL call with no knowledge of the host. The relative name is resolved against the **process current directory**, system32, so it throws `FileNotFoundException` for `C:\Windows\system32\tariffs.csv`. The same applies to `Directory.GetCurrentDirectory()`, `Path.GetFullPath` and relative paths read from configuration. ## Fixes, from best to bluntest - **Resolve against the content root**: inject `IHostEnvironment` and use `Path.Combine(env.ContentRootPath, "tariffs.csv")`, or `env.ContentRootFileProvider.GetFileInfo("tariffs.csv")`. - **Resolve against the binaries** for files that ship with the build: `Path.Combine(AppContext.BaseDirectory, "tariffs.csv")`. - **Configure absolute paths** for data that lives outside the install folder, for example under `ProgramData`, and read them from configuration. - **Move the content root deliberately**: `sc.exe create "Svc Name" binpath= "C:\Path\To\App.exe --contentRoot C:\Other\Path"` passes it as host configuration. - **Avoid** `HostApplicationBuilderSettings { ContentRootPath = Directory.GetCurrentDirectory() }` or `UseContentRoot(Directory.GetCurrentDirectory())`: under the service manager that puts the content root back in system32, and because the default JSON files are optional, configuration silently loads nothing. - `Directory.SetCurrentDirectory(AppContext.BaseDirectory)` at start-up also works, but it changes process-wide state that libraries may rely on; prefer explicit paths. ## What `AddWindowsService()` does and does not do The call lives in the `Microsoft.Extensions.Hosting.WindowsServices` package and is written as `builder.Services.AddWindowsService(o => o.ServiceName = "Queue Consumer")`: - It is **context aware**: it acts only when `WindowsServiceHelpers.IsWindowsService()` finds that the parent process is the services host (`services`). Under `dotnet run` or a terminal it does nothing and `ConsoleLifetime` stays in charge. - When active, it registers **`WindowsServiceLifetime`** (a `ServiceBase`) as `IHostLifetime`, so the service reports started to the Service Control Manager and stops when it is told to. - It adds the **Event Log** provider and defaults its source name to the application name. The default builder's filter on Windows sends only `Warning` and above to the Event Log unless the `Logging:EventLog` section says otherwise. - It does **not** change the content root or the current directory; the fallback described above comes from the default builder, which is why an empty builder or a hand-set content root loses it. A worker that must run both from a console and as a service needs no branching: keep `AddWindowsService()` unconditionally, and make every file path relative to `ContentRootPath` or `AppContext.BaseDirectory`. ## A deployment checklist for Windows Service workers - Publish to a fixed install folder and register that executable with `sc.exe create`, or `dotnet.exe` followed by the DLL path when you register the framework-dependent DLL instead of the app's executable. - Keep `appsettings.json` beside the executable; the Worker SDK copies it to the publish output and keeps it out of a single-file bundle. - Resolve every data file through `ContentRootPath`, `AppContext.BaseDirectory` or an absolute path from configuration. - Set the environment with a machine-level `DOTNET_ENVIRONMENT` variable or an `--environment` argument in the binary path; there is no launch profile under the service manager. - Make sure the start-up log for environment and content root reaches the Event Log, so the first support call can be answered from Event Viewer.
- Why does the same worker on Linux under systemd hit the opposite problem?On Linux the host takes the current directory as content root unconditionally; the system32 exception exists only on Windows. A unit without `WorkingDirectory=` does not start in the app folder, so the content root is wrong and the optional `appsettings.json` loads nothing. Set `WorkingDirectory=` in the unit, pass `--contentRoot`, or set `ContentRootPath` explicitly.
- How do you check which content root a running service picked?`WindowsServiceLifetime` logs "Application started. Hosting environment: …; Content root path: …" at `Information` under `Microsoft.Hosting.Lifetime`, but the Event Log provider's default filter is `Warning`, so the line never reaches Event Viewer. Lower the Event Log level for that category in the `Logging:EventLog` section, or log `ContentRootPath` yourself at `Warning`.
- AddWindowsService() sets the content root to AppContext.BaseDirectory.
- If appsettings.json loads, relative file paths must resolve to the same folder.
- Setting ContentRootPath to Directory.GetCurrentDirectory() makes a service portable.
- A Windows Service starts in the folder that holds its executable.
- AddWindowsService() must be removed for the app to run from a console.