views:

78

answers:

1

I need to check if any files in a folder is open by other applications or not. Unfortunately, if a file is open, the GetFileAttributesA() return wrong values. Is there a workaround for this or am I doing something wrong ?

+1  A: 

GetFileAttributes has nothing to do with file sharing. The only way to know if someone has the file open (thereby preventing you from opening it) is to try an open it yourself.

bool IsFileOpenBySomeoneElse(LPCTSTR pszFilename)
{
    HANDLE hfile = CreateFile(pszFilename, 
                              GENERIC_READ /*| GENERIC_WRITE*/, 
                              0, //0 is share-none
                              NULL,
                              OPEN_ALWAYS);
    if (hfile != INVALID_HANDLE_VALUE)
    {
       CloseHandle(hfile);
       return false;
    }
    return (GetLastError() == ERROR_SHARING_VIOLATION);
}   

But writing this function does you no good, because by the time you get around to opening th e file for processing, some other application may have the file open.

The only safe way to do this is to go ahead an do what you intend to do with the file, and when you try and open it for processing, notice the error value if you fail. Once you have the file open, you must keep it open until you are done or some other process can open it (or delete it!) behind your back.

John Knoeller
I agree with the "share-none". I don't agree with the "GENERIC_READ | GENERIC_WRITE". If CreateFile fails because the user only has read permission AND the file is also open by someone else, how do you know if GetLastError will give priority to the ERROR_SHARING_VIOLATION?
Windows programmer
@Windows Programmer: good point. but if you need write access, do you care? I guess it depends on why you are calling this function.
John Knoeller
Why do you assume Krishna needs write access? The question didn't say so.
Windows programmer
The problem is all these dont work when the file is already open. It will block all access to the information.
Krishna
@Windows Programmer: fair enough. I changed the code.
John Knoeller
@Krishna: what information? I don't understand what you are saying.
John Knoeller
Krishna's problem is that GetFileAttributesA() returns wrong information when another process has the file open. I haven't tried it but a wild guess might be that if another process is writing the file then this process's call to GetFileAttributes might not know the latest length.
Windows programmer

related questions