Users Pricing

blog

Home Blogs Create a Windows Service in .NET 10 the Easy Way – MindStick
Create a Windows Service in .NET 10 the Easy Way

Create a Windows Service in .NET 10 the Easy Way

Rajat Gupta 110 20 Nov 2026

Some jobs need to run all the time in the background: watching a folder for new files, syncing data with another system every few minutes, processing a queue, or sending scheduled notifications. On Windows Server, the natural home for these is a Windows Service. It starts with the machine, runs without anyone logged in, and restarts automatically if it fails.

Writing Windows Services used to involve a lot of ceremony. With modern .NET, it’s a small console-style project and one line of configuration.

Step 1: Create a Worker Service

dotnet new worker -n FileSyncService
cd FileSyncService
dotnet add package Microsoft.Extensions.Hosting.WindowsServices

The Worker Service template gives you a host with dependency injection, configuration and logging, plus a Worker class that runs in the background. The extra package adds Windows Service integration.

Step 2: Write the background work

Replace Worker.cs with something like this:

namespace FileSyncService;

public sealed class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IConfiguration _config;

    public Worker(ILogger<Worker> logger, IConfiguration config)
    {
        _logger = logger;
        _config = config;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var folder = _config["Sync:WatchFolder"] ?? @"C:\Data\Incoming";
        var interval = TimeSpan.FromSeconds(_config.GetValue("Sync:IntervalSeconds", 60));

        _logger.LogInformation("File sync started. Watching {Folder} every {Interval}", folder, interval);

        using var timer = new PeriodicTimer(interval);
        do
        {
            try
            {
                await ProcessFolderAsync(folder, stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break; // service is stopping
            }
            catch (Exception ex)
            {
                // Log and keep running; one bad file shouldn't stop the service
                _logger.LogError(ex, "Error while processing {Folder}", folder);
            }
        }
        while (await timer.WaitForNextTickAsync(stoppingToken));

        _logger.LogInformation("File sync stopping.");
    }

    private async Task ProcessFolderAsync(string folder, CancellationToken ct)
    {
        foreach (var file in Directory.EnumerateFiles(folder, "*.csv"))
        {
            ct.ThrowIfCancellationRequested();
            _logger.LogInformation("Processing {File}", file);

            // ... read, validate and import the file here ...
            await Task.Delay(100, ct);

            var done = Path.Combine(folder, "processed");
            Directory.CreateDirectory(done);
            File.Move(file, Path.Combine(done, Path.GetFileName(file)), overwrite: true);
        }
    }
}

Key points:

  • BackgroundService gives you ExecuteAsync, which runs when the service starts.
  • stoppingToken is cancelled when Windows asks the service to stop. Pass it everywhere so work stops promptly and cleanly.
  • PeriodicTimer runs the loop at a fixed interval without drifting or overlapping.
  • Catch exceptions inside the loop. An unhandled exception in ExecuteAsync stops the host, and in recent .NET versions that brings the whole service down by default. Logging and continuing is usually what you want for transient errors.

Step 3: Enable Windows Service hosting

Update Program.cs:

using FileSyncService;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddWindowsService(options =>
{
    options.ServiceName = "MindStick File Sync";
});

builder.Services.AddHostedService<Worker>();

var host = builder.Build();
host.Run();

AddWindowsService() does three useful things when running as a service:

  • tells Windows when the service has started and stopped
  • sets the content root to the app’s folder (by default, services start in C:\Windows\System32, which breaks relative paths)
  • enables logging to the Windows Event Log

When you run the app from a console during development, it simply runs as a normal console app. You can debug it like any other project.

Step 4: Configuration and logging

Add settings to appsettings.json:

{
  "Sync": {
    "WatchFolder": "D:\\Data\\Incoming",
    "IntervalSeconds": 30
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "SourceName": "MindStick File Sync",
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

Sending only warnings and errors to the Event Log keeps it readable. For detailed logs, add a file or centralised logging provider (for example Serilog or OpenTelemetry) as well.

Step 5: Publish

dotnet publish -c Release -r win-x64 --self-contained false -o C:\Services\FileSync
  • Framework-dependent (--self-contained false) requires the .NET 10 runtime on the server, but produces a small output.
  • Self-contained (--self-contained true) bundles the runtime, so the server needs nothing installed. Larger, but simpler to deploy. Add -p:PublishSingleFile=true for a single executable.

Step 6: Install the service

Open PowerShell as Administrator.

Using PowerShell:

New-Service -Name "MindStickFileSync" `
  -DisplayName "MindStick File Sync" `
  -Description "Imports CSV files from the incoming folder." `
  -BinaryPathName "C:\Services\FileSync\FileSyncService.exe" `
  -StartupType Automatic

Start-Service MindStickFileSync

Or with sc.exe (note the space after each =):

sc.exe create MindStickFileSync binPath= "C:\Services\FileSync\FileSyncService.exe" start= auto DisplayName= "MindStick File Sync"
sc.exe start MindStickFileSync

Set recovery options

Tell Windows to restart the service if it crashes:

sc.exe failure MindStickFileSync reset= 86400 actions= restart/60000/restart/60000/restart/300000

This restarts after one minute for the first two failures and after five minutes for subsequent ones, resetting the failure count daily.

Step 7: Choose the right account

By default, services created this way run as LocalSystem, which has very broad rights. That’s more than most services need.

Better options:

  • A virtual service account, such as NT SERVICE\MindStickFileSync, which Windows manages automatically and which you can grant specific folder permissions.
  • A dedicated domain account or group Managed Service Account (gMSA) if the service needs network resources like file shares or SQL Server with Windows authentication.

Grant only the permissions needed: read on the incoming folder, modify on the processed folder, and database rights for the specific tables.

Updating the service

Stop-Service MindStickFileSync
# copy the new published files over the old ones
Start-Service MindStickFileSync

Automate this in your deployment pipeline. To remove the service entirely: sc.exe delete MindStickFileSync.

Common problems

The service starts and stops immediately. Check the Event Viewer → Windows Logs → Application for exceptions. Typical causes: missing configuration, a folder that doesn’t exist, insufficient permissions, or the .NET runtime missing for framework-dependent builds.

Relative paths don’t work. Without AddWindowsService(), the working directory is System32. Use AppContext.BaseDirectory or absolute paths from configuration.

“Error 1053: The service did not respond to the start request in a timely fashion.” Usually the app crashed during startup, or long-running work is happening before the host starts. Keep startup quick and do heavy work inside ExecuteAsync.

Network folders aren’t accessible. LocalSystem and virtual accounts access the network as the computer account. Use a domain account or gMSA with the correct share permissions, and use UNC paths (\\server\share), not mapped drive letters, which don’t exist for services.

When to use something else

  • A job that runs once a day: a scheduled task may be simpler than an always-running service.
  • Web requests: host an ASP.NET Core app in IIS or as a Kestrel service instead.
  • Cloud-hosted background work: consider Azure Functions, a container, or a queue-triggered worker.

The takeaway

With the Worker Service template and AddWindowsService(), a .NET 10 Windows Service is just a background class with proper cancellation, configuration and logging. Publish it, install it with PowerShell or sc.exe, set recovery options, and run it under a least-privilege account.

The result is a background process that starts with the server, recovers from failures, and is as easy to develop and debug as any other .NET app.


Rajat Gupta

Java Developer at Postman

Hi, I am Rajat. I work as a Java Developer at Postman and my work is mostly about Java and Spring Boot backend development. Before this I spent 3 years at Paytm. I studied B.Tech in Information Technology from IIIT Hyderabad. I am originally from Prayagraj, Uttar Pradesh. Weekends are for yoga.


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md