I need to check if a file is in use before I try to get access to it. Is there way to do it in Lazarus environment?
-
`try...except` construct is not good enough for you? – David Jashi Jul 26 '13 at 18:53
2 Answers
Open the file with FileOpen(FileName, fmOpenReadWrite or fmShareExclusive)
and check the result.
Update (thanks to Ken White's comment). This is not the direct answer to your question as FileOpen
actually gets access to the file, but you shouldn't perform the check and then open the file, otherwise you'll get a race condition. You should open the file and then check if the open succeeded.
Opening a file with FileOpen
and accessing the file through its handle may seem unfamiliar. You can achieve the same goal when opening a file with e.g. Rewrite
inside a try-except
block. I am not sure about Lazarus, but in Delphi using try-except
with high-level file routines requires explicit resetting IOResult in case of exception (put SetInOutRes(0)
into except
section), otherwise the following file operation fails.

- 11,008
- 1
- 23
- 18
-
Certainly. I should add to my answer that the test should be performed at the same time as getting access, otherwise there will be a race condition. There are other ways like opening a file inside try-except block. Using `FileOpen` just gives an exception-free way to perform the check. – nullptr Jul 26 '13 at 18:59
You don't. You try to open it, and handle the exception if and when you can't.
Checking to see if it's in use first serves no purpose.
Your code to see if it's in use says it's not
--->>> Another app opens the file, locking it
Your code to open file fails
Instead, use a normal try..except
block:
try
FS := TFileStream.Create(YourFileName, fmOpenReadWrite, fmShareExclusive);
// Code to use file here
except
// Handle failure to access file
end;

- 123,280
- 14
- 225
- 444
-
Or use $I+/I- and check ioresult if your I/O is not stream based. – Marco van de Voort Jul 27 '13 at 12:28