I have an app that works well as a cmd line app, but when running as a service, the FileSystemWatcher stops working.
I have validated that the service has access to the files as it's using the same files elsewhere in the service.
My BackgroundService is setup like this:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private FileSystemWatcher _watcher, _watcher2;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
SetupFileSystemWatchers();
return Task.CompletedTask;
}
}
Here is how my FileSystemWatchers are set up:
private void SetupFileSystemWatchers()
{
try
{
_watcher = new FileSystemWatcher
{
Path = @"\\10.10.1.10\files$\1\2\3\",
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName
};
_watcher.Created += async (sender, e) =>
{
_logger.LogInformation("Created");
await FileWatcherFileChanged(sender, e);
};
_watcher.EnableRaisingEvents = true;
_watcher2 = new FileSystemWatcher
{
Path = @"\\10.10.1.10\files$\1\2\4\",
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName
};
_watcher2.Created += async (sender, e) =>
{
_logger.LogInformation("Created");
await FileWatcherFileChanged(sender, e);
};
_watcher2.EnableRaisingEvents = true;
_logger.LogInformation("Watchers set up successfully.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error setting up file system watchers.");
}
}
private async Task FileWatcherFileChanged(object source, FileSystemEventArgs e)
{
await _manage.RepoChanged(e.FullPath);
}
}
I have traces all over my code to figure what happens and it seems everything is initialized properly, but then event just does not get triggered when run as a service. Same exact code run as a console app on the same server and it works perfectly.