Determining if a File is Opened by another Application
Keywords: fileopen file open
Question:
If a file is currently opened by another application but not in read-deny mode, how can WinBatch
determine that it is opened?
Answer:
Depends.
No good code to merely check if a file is open or not.
We can tell if it is open for writing, (FileExist can do that - usually), but we cannot tell if it just
open for reading.
FOR TESTING MAKE SURE YOU HAVE BACKUPS OF THE FILE. IT GONNA BE EASY TO
CLEAR IT.
Try 1:
a=FileExist("thefile")
if a==0 then message("Try 1","Not found")
if a==1 then message("Try 1","Available")
if a==2 then message("Try 1","In Use")
Try 2:
ErrorMode(@OFF) ; *see note
a=FileOpen("thefile","APPEND")
ErrorMode(@CANCEL)
if a!=0
...FileClose(a)
message("Try 2","File available")
else
...message("Try 2","File not available")
endif
NOTE: Do not consider using ErrorMode(@OFF) until you have read the all the documentation on it
and fully understand all the examples of what not to do in the documentation. NEVER leave Errormode
OFF for more than 1 line of code.
Question (continued):
Neither method seems to work. The files I am interested are txt files opened by a text editor. Whether
they are opened or not they are still available with FileExist or FileOpen functions. Any other ideas?
Answer:
- Try a manual test. Open the file with the text editor.
- Then try to open it with notepad.
if that works change some text in the Notepad window and try to save it.
- Close the editor. Do not save any data. Examine the file. If the changes made in notepad are there, then
the file was not "open" at the time notepad read it in and saved it.
- In Windows many editor type programs open the file, read it into memory, and close the file...allowing
other applications access.
- For experimenting....
- Notepad is of the above type. It opens, reads, and closes the file.
- Microsoft Word, on the other hand, opens the file and leaves it open for the duration.
You can experiment and see what kind you have.
Question (continued):
My text editor is clearly of the first type (files are loaded into memory then closed); so I guess the question
becomes how to determine whether a particular file is loaded into memory.
Answer:
Very difficult.
If your editor displays the file name in the title bar you could
list=WinItemize()
list=strlower(list)
;check strindex parameters...
a=StrIndex(list,FileNameRoot("filename"),0,@fwdscan)
if a!=0 then message("Hmmm","looks like file might be open")
Also see the article:
http://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/nftechsupt.web+WinBatch/Error~Codes+1077~File~Open~Failed.txt
Article ID: W13072
Filename: FileOpen and Determing if File is Open.txt
File Created: 2017:08:29:11:48:30
Last Updated: 2017:08:29:11:48:30