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
2010-02-02 02:53:33
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
2010-02-02 03:52:25
@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
2010-02-02 03:56:04
Why do you assume Krishna needs write access? The question didn't say so.
Windows programmer
2010-02-02 05:11:33
The problem is all these dont work when the file is already open. It will block all access to the information.
Krishna
2010-02-02 05:39:29
@Windows Programmer: fair enough. I changed the code.
John Knoeller
2010-02-02 05:47:20
@Krishna: what information? I don't understand what you are saying.
John Knoeller
2010-02-02 05:50:35
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
2010-02-02 07:47:41