Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

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.

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top