I'm trying to watch a directory for newly added files ending in .csv
do something with them, delete the file and wait for a newly added file to do process the file again. I'm using a BackgroundService
with the following code:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IProcessFileService _processFileService;
private ApplicationOptions _applicationOptions;
private FileSystemWatcher _watcher = new();
public Worker(ILogger<Worker> logger, IProcessFileService processFileService, IOptions<ApplicationOptions> applicationOptions)
{
_logger = logger;
_processFileService = processFileService;
_applicationOptions = applicationOptions.Value;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
string filePath = _applicationOptions.InputDirectory;
_watcher.Path = filePath;
_watcher.EnableRaisingEvents = true;
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite;
_watcher.Filter = "*.csv*";
_watcher.Created += new FileSystemEventHandler(OnFileCreated);
return Task.CompletedTask;
}
private async void OnFileCreated(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
await HandleAddedFile();
}
}
private async Task HandleAddedFile()
{
try
{
await _processFileService.ProcessFile();
}
catch(Exception ex)
{
_logger.LogError("{error}", ex.Message);
}
_processFileService.DeleteFileAndLog();
}
}
Works fine for the first time, but when trying inserting a second file in the directory, I get the error: The process cannot access the file "PATH" because it is being used by another process.
Processing the label includes some async work, how can I fix this issue?