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?
5 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 :)
-
2+1, and I'd love to vote this up more often. This whole "check for something, then act accordingly" seems to be either a remnant of the olden DOS (or other single-tasking) days, or it's just that programmers like to think their program is all alone on a computer...– mghieFeb 2, 2009 at 13:35
There is a new way to get the origin of file locking for Vista and up here: http://www.remkoweijnen.nl/blog/2011/01/03/cannot-access-files-but-need-the-origin/
UserMode: The best way to write to a locked file is to ask the user to close it in the other process. In batch processes you should ignore such a file and log the problem. Providing the name of the other process is a very good way to find a solution for the user.
Not sure in which programming language you'd like to check if you can write to a file. In Java, java.io.File.canWrite() can do the job for you.
General:
In UNIX-like OS, you can use the lsof command.
If you want to see which program holds a handle to your file, use the Process Monitor (download from MicroSoft).
This tool has a command line interface, so you could use your language's scripting interface (for example java.lang.Process
) to run the tool and display a useful error message.
IsFileInUse as given in http://delphi.about.com/cs/adptips1999/a/bltip0999_3.htm
-
1That's a horrible version of it. Much better is the one by Johnjces at: experts-exchange.com/Programming/Languages/Pascal/Delphi/…– lkesslerSep 8, 2010 at 1:30
-