C
C#2y ago
Zaina

❔ 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); }
}
5 Replies
ero
ero2y ago
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.
Zaina
ZainaOP2y ago
So what can be the solution ?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega2y ago
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
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server