Ofer
Ofer

Reputation: 333

FindFirstChangeNotification is notifying about changes twice

I want to monitor a folder in my file system. Let say I want to monitor the folder: C:\MyNewFolder

I have this code to do it:

HANDLE  ChangeHandle=FindFirstChangeNotification(_T("C:\\\MyNewFolder"),FALSE,FILE_NOTIFY_CHANGE_LAST_WRITE);
for(;;)
{
    DWORD Wait=WaitForSingleObject(ChangeHandle,INFINITE);
    if (Wait == WAIT_OBJECT_0)
    {
        MessageBox(NULL,_T("Change"),_T("Change"),MB_OK);
        FindNextChangeNotification(ChangeHandle);
    }
    else
    {
        break;
    }
}

I want to have a messagebox that notifying me about any file change in my folder. That code works fine but I have one problem. The problem is that I got 2 notification for each change. What is the problem with my code? Thanks.

Upvotes: 8

Views: 8381

Answers (2)

Hans Passant
Hans Passant

Reputation: 942099

This is entirely normal. A change to a file usually involves a change to the file data as well as a change to the directory entry. Metadata properties like the file length and the last write date are stored there. So you'll get a notification for both. ReadDirectoryChangesW() doesn't otherwise distinguish between the two.

This is not different from a process making multiple changes to the same file. Be sure to be able to handle both conditions. This usually involves a timer so you don't go overboard with the number of operations you perform on a notification. Such a timer is also often required because the process that is changing the file still has a lock on it that prevents you from doing anything with the file. Until the process closes the file, an indeterminate amount of time later.

Upvotes: 12

Jonathan Potter
Jonathan Potter

Reputation: 37192

What you're probably seeing is multiple changes to the one file (e.g. a file being created, and then written to, or a file being written to multiple times, etc). Unfortunately FindFirstChangeNotification doesn't tell you what has actually happened.

You're better off using ReadDirectoryChangesW for file notification as it will actually tell you what has changed.

Upvotes: 2

Related Questions