How do I determine whether a file is in use?
-
13-09-2019 - |
Question
How can I determine whether a file is in use via VBScript or a batch file? It can be a separate utility.
I've had a look at Handle but sometimes the handles don't line up with filenames, e.g. some DLLs, and it doesn't do partial searches (though I could presumably use some of the text processing utils on its full output to handle that side of things).
Solution 3
What I have ended up using is ListDLLs. Running "listdlls -d | find /c "pid" > temp.txt" and then testing whether there's any data in temp.txt seems to determine whether or not a file is in use successfully.
OTHER TIPS
Can you simply attempt to do whatever you want to do to the file, and report an error if it fails with a sharing violation?
"It's easier to ask forgiveness than it is to get permission." - Grace Hopper
Or if you want to know in advance whether an attempt to do something destructive will succeed, you could attempt to do something non-destructive that requires the same permissions. So if you want to know whether you can overwrite a file, try to open it for appending but don't write anything.
Whatever you do, you'll need to beware race conditions - what if someone else opens the file between your test and your actual operation?
Try this:
@echo off
echo.N|copy /-y NUL "%~1">NUL
if not errorlevel 1 echo not in use
if errorlevel 1 echo in use
Credit: DosTips.com :IsFileOpen