What is the programmatic way to determine if a file is open on Windows?

Is there an easy way to determine if a file is open in any process on Windows?

For example, I control the directory, and if the files are placed in the directory, I want to perform some actions on these files.

I do not want to perform these actions if the files are still being copied to the directory or if the contents of these files are still being updated.

So what happens if a file name is given, I want to implement a function, for example, the IsFileOpenedAnywhereElseInAnyProcess(const PathName: string): Boolean function, which returns either true or false .

One of the ways I can think of is to rename the file, and if the renaming succeeds, no other processes have opened the file of interest to me, for example:

 function IsFileOpenedAnywhereElseInAnyProcess(const PathName: string): Boolean; begin Result := not (MoveFileEx(PathName, PathName+'.BLAH', 0) and MoveFileEx(PathName+'.BLAH', PathName, 0)); end; 

Logic, if I can rename a file (to another extension), then rename it back, it does not open by any other process (during verification).

Thanks.

+6
source share
1 answer
 IsFileOpenedAnywhereElseInAnyProcess(const PathName: string): Boolean 

This is a feature that you can never implement correctly in a multi-tasking operating system. You will get a False return and a nanosecond later, another process will open the file and ruin your day.

The only way to do it right is to do it atomically, actually trying to open the file. And indicate no sharing so that no other process can open the file. This will happen with ERROR_SHARING_VIOLATION if another process has already accessed the file. At this point, you will wait a while and try again later.

+8
source

All Articles