Checking for open files in a given directory tree

76 views Asked by At

Is there a way to determine with C+++ if any file is open in a given directory tree?

Cmd.exe knows instantly if I attempt to rename a folder and a file within that directory tree is currently open. I've used API Monitor to determine that cmd.exe uses NtOpenFile() followed by NtSetInformationFile with FileRenameInformation and that returns STATUS_ACCESS_DENIED when a file is open but I've not been able to determine what's happening at a lower level.

I'm trying to ensure no files are open before beginning a batch process without having to check each file individually as there could be hundreds of thousands of files in the directory tree.

Can anyone expand on this?

Thanks, Steve Thresher.

1

There are 1 answers

0
Paul Sanders On

You will have to check each file individually, I think. That said, this should do it:

HANDLE hFile = CreateFile
    (my_filename, GENERIC_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile == INVALID_HANDLE_VALUE)
{
    DWORD err = GetLastError ();
    if (err == ERROR_SHARING_VIOLATION)
    {
        // File is already open
    }
}
else
    CloseHandle (hFile);

Note that dwShareMode is passed as 0, which prevents Windows opening the file if it is already opened elsewhere.