tags:

views:

98

answers:

3

Possible Duplicate:
C#: Is there a way to check if a file is in use?

I'm using the System.IO.File class to delete a file, but of course this causes an exception if it's being used. I don't just want to catch the exception and forget about it (that would be using an exception as a flow construct); I'd like to know how to check whether my file is being used by another process. What am I looking for?

A: 

The solution posted in the accepted answer should do what you're looking for.

http://stackoverflow.com/questions/876473/c-is-there-a-way-to-check-if-a-file-is-in-use

Laplace
So opening the file and catching the exception before deleting the file is better than deleting the file and catching the exception?
dtb
No, you should try to delete the file and catch any exception. If you open the file first, then it might not be locked when you open it (no exception), but then become locked just before you try to delete it. Classic race condition. The answer in the link is IMHO poor, as it suffers from this race condition.
ShellShock
+9  A: 

Actually, "using an exception as a flow construct" is exactly the right thing to do here. Try to delete the file; if you get an access denied exception, then let the user know.

JSBangs
+1 Actually, if you try to delete an in-use file in windows explorer or something, there is an obvious delay in which the system tries to delete the file before reporting that it is in use by another process. This makes me think there is no such API call anywhere, not even in the windows system.
NYSystemsAnalyst
+1 Acquiring permissions for actions on a file is always a race condition. First try doing what you need to do (delete the file, in this case) then deal with the consequences of possible failure.
Curt Nichols
+1 Agreed, try and delete the file and catch the FileIOException if it fails. I have found no other way to deal with this issue.
Justin
+4  A: 

Even if you do find some API call, you will still need to cope with the situation where the file goes from being not in use to being in use between the time you check and the time you actually attempt the deletion. The correct thing to do here is to catch the exception.

AakashM