Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: Check whether file is in use

I want to write to/delete a file but sometimes I get a crash if the file is in use by another program. How do I check to see whether the file is opened by another process or I can open it for writing?

like image 768
Arthur Avatar asked Feb 02 '09 12:02

Arthur


1 Answers

The problem is, that between the time you check to see if you could get exclusive access and opening the file, something else gets exclusive access to the file, and you get the exception anyway.

The only fool proof way to see if you can get an exclusive lock on a file is to try and get an exclusive lock on the file, if you get it you have it.

If not, you catch the exception, and either

  • Go do something else
  • Wait a while and try again

It's one of life’s situations where it's better to ask for forgiveness than permission :)

like image 69
Binary Worrier Avatar answered Oct 22 '22 21:10

Binary Worrier