I'm trying to cerate an simple application that is listening to a folder, and everytime a new file is created, moved or copyed to that folder i want to get a notification.
So i created a simple application that creates a seperate thread where i call
ReadDirectoryChangesW
.
To do this infinitely i have done it into a while(true) loop.
The code is pretty simple (i use ReadDirectoryChangesW in synchronus mode)
while(TRUE)
{
BYTE byBuffer[32 * 1024]; DWORD dwOffset = 0;
TCHAR cFile[MAX_PATH];
DWORD dwBytesRet;
PFILE_NOTIFY_INFORMATION pNotify;
ReadDirectoryChangesW(pWatcher->m_hDir, byBuffer, sizeof(byBuffer), 0, pWatcher->m_dwNotifyFilter, &dwBytesRet, NULL, NULL);
do
{
pNotify = (PFILE_NOTIFY_INFORMATION) &byBuffer[dwOffset];
dwOffset += pNotify->NextEntryOffset;
INT nCount = WideCharToMultiByte(CP_ACP, 0, pNotify->FileName, pNotify->FileNameLength / sizeof(WCHAR), cFile, MAX_PATH - 1, NULL, NULL);
cFile[nCount] = TEXT('\0');
}
while(pNotify->NextEntryOffset != 0);
}
The problem is now, that for every new created file i get two notifications.
It do it in the following order:
ReadDirectoryChangesW
returns with the new created file- move into the do-while loop
- get the
pNotify
-pointer - calculate the offset
- Copy the buffer into a TCHAR-array
- Notify me
up to this point everything is ok
NextEntryOffset
== 0, so jump outside the do-while loop- now loop begins again and run to
ReadDirectoryChangesW
ReadDirectoryChangesW
returns immediately- Steps 2-8 again
- Execution hold on
ReadDirectoryChangesW
until a new file is created
I have searched at the internet and found this looks lika a common bug. So i have tried to work around the bug with a second string. I compare the second string to the string stored in cFile[] and if they are different, i save cFile to my second string and notify.
That work's fine if only one file is created at a time. But if i copy a bundle of files (for example 4) the solution won't work, because the files doesn't come ordered (if i say ordered i mean File 1, File 1, File 2, File 2, ... they come more like File 1, File 2, File 3, File 4, File 3, File 1, File 4).
So i hope you guys from CodeProject could help me; is there any usable (and pretty) solution for this problem out there?
I' so happy to hear some solutions or ideas from you!
Thank you so much in advance!