❔ FILewatcher raise multiple events when a file is created
Hello everyone. I have a code that alert me when a file is created in a folder (the file is created by an external process). the problem is that the event Handlecreated is raised multiple times for a single file. Does anyone know why ?
this is the code :
string extractionFolder = @"C:\Extractions";
FileSystemWatcher watcher = new FileSystemWatcher(extractionFolder);
watcher.Filter = "*.csv";
watcher.Created += HandleCreated;
watcher.Error += HandleError;
watcher.EnableRaisingEvents = true;
private async void HandleCreated(object sender, FileSystemEventArgs e)
{
int readAttempt = 0; int maxDuration = 15; while (!IsFileReady(e.FullPath) && readAttempt < maxDuration) { readAttempt++; System.Threading.Thread.Sleep(1000); } if (IsFileReady(e.FullPath)) {
await _hubContext.Clients.All.SendAsync("ReceiveMessage", e.FullPath); }
}
int readAttempt = 0; int maxDuration = 15; while (!IsFileReady(e.FullPath) && readAttempt < maxDuration) { readAttempt++; System.Threading.Thread.Sleep(1000); } if (IsFileReady(e.FullPath)) {
await _hubContext.Clients.All.SendAsync("ReceiveMessage", e.FullPath); }
}
5 Replies
https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.created?view=net-7.0#remarks
Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
So what can be the solution ?
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
you could upon incoming events write down the important details (file path, time of event) and check if you've seen that before recently, filtering the list to the last few seconds or so at the end of the handler
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.