CloudyMarble
CloudyMarble

Reputation: 37566

Checking if a file is in use without try catch?

Is there a way I can check if a file is in use or is not opened by other process without just trying to open it and catching an exception? Is there no service method to test such a thing?

Upvotes: 14

Views: 5443

Answers (4)

Kimate Richards
Kimate Richards

Reputation: 150

You could implement this guy in .net 4.5 but it includes a lot of overhead http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

Upvotes: 0

CloudyMarble
CloudyMarble

Reputation: 37566

Interesting way to avoid try catch (but implies an attempt to open) is the LockFile() or CreateFile() functions:

HANDLE WINAPI CreateFile(...)

If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.


BOOL WINAPI LockFile(...)

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, the return value is zero (FALSE). To get extended error information, call GetLastError.

This locks the specified file for exclusive access by the calling process, and on failure writes error information to the thread's last-error, which can be retreived using the GetLastError function.

It would still be thinkable that between the unlockFile and OpenFile another process could lock the file, but it possible to minimize this period by keeping the file locked just to the moment it needs to be opened.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612804

Can I test if a file can be opened without attempting to open it?

The .net framework, just like the Windows API beneath, provides no such functionality. If you wish to know whether or not a file can be opened you are expected to attempt to open it and check for failure.

Upvotes: 3

Cody Gray
Cody Gray

Reputation: 244712

Even if there was, it wouldn't do you much good since you would still have to catch the exception in order to handle the race condition where the file became unavailable in between your initial check and your actual attempt to open/access it.

I can't think of any compelling advantage to a preliminary defensive check. It just results in unnecessary code duplication.

If there were such a IsFileAccessible function, it would probably be implemented as a giant try/catch block that attempted to open the file, caught failures, and returned the result.

Upvotes: 15

Related Questions