florin
florin

Reputation: 405

FileWatcher fires change event after file deletion

I'm using a FileWatcher to trigger processing of files as soon as they are added to a folder. After the file it is processed it is deleted.

My problem is that after the file is deleted I get another file change event which is so close to the deletion than in some cases checking for File.Exists it tells that the file still exists. But of course some milliseconds later when looking to process the file it does not really exists. The FileWatcher is set to notify on NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Attributes

Thanks, florin

Upvotes: 0

Views: 1353

Answers (3)

Collin
Collin

Reputation: 11

Save to say, it's been a while since this was asked, but seeing as I asked myself, if the change event will indeed be triggered when a file is deleted I thought I might as well chip in an answer.

To prevent your OnChange event from following through, you can check the FileSystemEventArgs for the WatcherChangeType and simply return, on a deleted event.

private static void OnChanged(object sender, FileSystemEventArgs e)
{
    if (e.ChangeType == WatcherChangeTypes.Deleted)
    {
        return;
    }
    Console.WriteLine($"Changed: {e.FullPath}");
}

Upvotes: 0

Amsakanna
Amsakanna

Reputation: 12934

usually filewatcher fires multiple times since the fileChange is a series of events. Here is a useful link. http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx Scroll to the end.

Upvotes: 0

Oliver
Oliver

Reputation: 45071

If you take a little search on SO, you'll find plenty of questions, where people like to check if they are able to access a file or if they have the rights needed.

The problem is, that even if you check it (like you do with File.Exists()) the situation can be changed when it comes to the real operation.

So just throw out the File.Exists() and put a try catch around your deletion operation.
If it fails, it's up to you to decide if you just drop it silently, inform the user, close your application, shutdown the pc, etc.

Upvotes: 1

Related Questions