Recipe 10.3 · C#
FileSystemWatcher Done Right
Problem
A service needs to process files as they arrive in a folder. FileSystemWatcher looks like the answer, and then the bugs start. It raises Created and several Changed events for one file. It raises Created before the writer has finished, so the file is locked or incomplete. It drops events when many files arrive at once. And files that arrive while the service is stopped are never seen at all.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
watcher.Created += (s, e) =>
{
string text = File.ReadAllText(e.FullPath);
Import(text);
File.Delete(e.FullPath);
};
watcher.EnableRaisingEvents = true;
ReadAllText fails with "file in use" for anything larger than a few kilobytes, and the exception is lost on a thread-pool thread. A bulk copy of 500 files overflows the watcher's buffer and some files are never processed.
The improved recipe
Treat the watcher as a hint, not the source of truth. Its events only put a path on a queue. One consumer takes paths from the queue, waits until each file can be opened exclusively, and processes it. On startup and whenever the watcher reports an error, a full scan of the folder queues everything that is there, so nothing is missed.
NuGet package: Microsoft.Extensions.Hosting.Abstractions.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Files;
public abstract class FolderWatcherService : BackgroundService
{
private readonly Channel<string> _queue =
Channel.CreateUnbounded<string>(
new UnboundedChannelOptions { SingleReader = true });
private readonly ConcurrentDictionary<string, byte> _queued =
new(StringComparer.OrdinalIgnoreCase);
protected FolderWatcherService(
string folder, string filter, ILogger logger)
{
Folder = folder;
Filter = filter;
Logger = logger;
}
protected string Folder { get; }
protected string Filter { get; }
protected ILogger Logger { get; }
protected abstract Task ProcessFileAsync(
string path, CancellationToken ct);
protected override async Task ExecuteAsync(CancellationToken ct)
{
Directory.CreateDirectory(Folder);
using var watcher = new FileSystemWatcher(Folder, Filter)
{
NotifyFilter = NotifyFilters.FileName
| NotifyFilters.LastWrite
| NotifyFilters.Size,
InternalBufferSize = 64 * 1024
};
watcher.Created += (_, e) => Enqueue(e.FullPath);
watcher.Changed += (_, e) => Enqueue(e.FullPath);
watcher.Renamed += (_, e) => Enqueue(e.FullPath);
watcher.Error += (_, e) =>
{
Logger.LogWarning(e.GetException(),
"Watcher error on {Folder}; rescanning", Folder);
EnqueueExisting();
};
watcher.EnableRaisingEvents = true;
EnqueueExisting();
await foreach (string path in _queue.Reader.ReadAllAsync(ct))
{
_queued.TryRemove(path, out _);
if (!File.Exists(path))
{
continue;
}
try
{
if (await WaitUntilReadyAsync(path, ct))
{
await ProcessFileAsync(path, ct);
}
else
{
Logger.LogWarning("{Path} stayed locked", path);
Enqueue(path);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Logger.LogError(ex, "Failed to process {Path}", path);
}
}
}
private void EnqueueExisting()
{
foreach (string path in Directory.EnumerateFiles(Folder, Filter))
{
Enqueue(path);
}
}
private void Enqueue(string path)
{
string name = Path.GetFileName(path);
if (name.StartsWith('.') || name.EndsWith(".tmp",
StringComparison.OrdinalIgnoreCase))
{
return;
}
if (_queued.TryAdd(path, 0))
{
_queue.Writer.TryWrite(path);
}
}
private static async Task<bool> WaitUntilReadyAsync(
string path, CancellationToken ct)
{
for (int attempt = 0; attempt < 30; attempt++)
{
try
{
using var probe = new FileStream(path, FileMode.Open,
FileAccess.Read, FileShare.None);
return true;
}
catch (IOException) when (File.Exists(path))
{
await Task.Delay(TimeSpan.FromSeconds(1), ct);
}
}
return false;
}
}
A usage snippet for a concrete service. It only implements the processing step, and it must move the file when done so a rescan does not process it again:
public sealed class InvoiceDropService(ILogger<InvoiceDropService> log)
: FolderWatcherService(@"D:\drop\invoices", "*.csv", log)
{
protected override async Task ProcessFileAsync(
string path, CancellationToken ct)
{
await ImportInvoicesAsync(path, ct);
string done = Path.Combine(Folder, "processed",
Path.GetFileName(path));
Directory.CreateDirectory(Path.GetDirectoryName(done)!);
File.Move(path, done, overwrite: true);
}
private static Task ImportInvoicesAsync(
string path, CancellationToken ct) => Task.CompletedTask;
}
How it works
The event handlers do almost nothing: they call Enqueue, which ignores temp files and adds the path to the channel only if it is not already queued. Five Changed events for one file become one queue entry. Because the handlers return immediately, the watcher's internal buffer drains quickly, which is the best defense against overflow. The buffer is also raised to 64 KB, the largest size Microsoft recommends.
The consumer is a single loop, so files are processed one at a time in arrival order, and exceptions are caught and logged per file instead of vanishing on a thread-pool thread. WaitUntilReadyAsync tries to open the file with FileShare.None. That fails while any other process has the file open, so a successful open means the writer is done. After 30 seconds of failures the path is put back on the queue for later.
EnqueueExisting runs at startup, to pick up files that arrived while the service was stopped, and on every Error event, which is how the watcher reports a buffer overflow. Since processed files are moved away, a rescan only finds work that is still pending. The watcher becomes a way to react quickly; the scan is what makes the service correct.
Variations and pitfalls
- Network folders. Watchers on UNC paths lose their connection when the file server restarts, and the
Errorevent is the only clue. Add a periodic scan, every few minutes, with aPeriodicTimer(Chapter 14). - Ask senders to rename. The most reliable drop protocol is for the sender to upload as
name.tmpand rename when finished. The watcher then sees aRenamedevent for a complete file. - Poison files. A file that always fails is logged on every rescan. Move failures to an
errorsubfolder after a few attempts.