.NET

From Theory to Practice: Building a File Watcher Service

A Worker Service that watches a folder and processes new files as they land: configuration, file handling, and installing it as a service.

The Worker Services guide covered the fundamentals. This one puts them to work on a real example, a File Watcher Service that’s ready for production.

The problem

You need to monitor a directory for new files, say for processing financial transactions or handling automated data imports. So you need a service that:

  • Runs continuously
  • Monitors a specific directory
  • Processes new files as they arrive
  • Maintains security and stability
  • Restarts automatically if it fails

The solution

We’ll take a plain Worker Service and add file system monitoring to it.

Step 1: Basic structure

First, the Worker class, with what it needs for watching files:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private FileSystemWatcher? _watcher;
    private readonly string _watchPath;
    private readonly string _fileFilter;

    public Worker(ILogger<Worker> logger, IConfiguration configuration)
    {
        _logger = logger;
        // Get watch path from configuration
        _watchPath = configuration.GetValue("WatchSettings:FolderPath")
            ?? throw new ArgumentNullException("WatchSettings:FolderPath must be set");
        _fileFilter = configuration.GetValue("WatchSettings:FileFilter") ?? "*.txt";
    }
}

Step 2: Configuration

In appsettings.json we define what to watch:

{
  "WatchSettings": {
    "FolderPath": "C:\\WatchFolder",
    "FileFilter": "*.txt"
  }
}

Step 3: Implementing the file watcher

Now the file watching logic:

public override Task StartAsync(CancellationToken cancellationToken)
{
    _logger.LogInformation("Worker starting at: {time}", DateTimeOffset.Now);
    
    // Ensure directory exists
    if (!Directory.Exists(_watchPath))
    {
        Directory.CreateDirectory(_watchPath);
        _logger.LogInformation("Created watch directory: {path}", _watchPath);
    }

    // Initialize FileSystemWatcher
    _watcher = new FileSystemWatcher
    {
        Path = _watchPath,
        Filter = _fileFilter,
        NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
        EnableRaisingEvents = true
    };

    // Hook up events
    _watcher.Created += OnFileCreated;
    _watcher.Error += OnError;

    return base.StartAsync(cancellationToken);
}

Step 4: File processing logic

This is how we handle new files:

private void OnFileCreated(object sender, FileSystemEventArgs e)
{
    try
    {
        _logger.LogInformation("New file detected: {file}", e.Name);
        
        // Wait briefly to ensure file is completely written
        Thread.Sleep(100);

        // Process the file
        ProcessFile(e.FullPath);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error processing file: {file}", e.Name);
    }
}

Step 5: Service installation

To install it as a Windows Service:

# Create the service
sc.exe create "TSVAutomation" binpath= "C:\path\to\service.exe" start= auto

# Configure automatic restart
sc.exe failure "TSVAutomation" reset= 86400 actions= restart/60000/restart/60000/restart/60000

The practices built into it

  1. Configuration management. The configuration is external, in appsettings.json, it supports environment-specific settings, and the service fails fast when a required setting is missing.
  2. Error handling. File system errors are handled gracefully, every important event is logged, and exceptions are caught where they happen.
  3. Resource management. The FileSystemWatcher gets disposed, shutdown is clean, and file processing is careful with memory.
  4. Reliability. The service restarts automatically, it avoids file locks, and it recovers from errors.

Before you run it in production

  1. Security. Set proper file access permissions, process sensitive data securely, and keep audit logs for file operations.
  2. Performance. Batch the processing when many files arrive, throttle resources, and monitor file processing times.
  3. Maintenance. Rotate the logs, monitor performance, and add health checks.

How it connects to the fundamentals

This one service uses most of what a Worker Service is: background processing, resource management, error handling, configuration, logging, and service lifetime management. It also shows the kind of real problem Worker Services are good at, which is monitoring something continuously, handling system events, processing data reliably, and managing resources efficiently while doing it.

Next steps

To take this service further, consider:

  1. Adding file archiving
  2. Implementing retry logic
  3. Adding email notifications
  4. Creating a monitoring dashboard
  5. Implementing health checks

This is a foundation you can build on for your own needs, whether that’s processing financial data, system automation, or file-based workflows. What makes a Worker Service good is the balance between what it does and how reliable, secure and maintainable it is.


Have questions about implementing your own Worker Service? The previous guide covers the Worker Service fundamentals.


Have a .NET modernization project?

Free 30-minute call. No pitch, we just look at your migration together.

Get in touch