Checking if a file is in use without try catch?

前端 未结 4 1915
一向
一向 2020-12-18 23:09

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

相关标签:
4条回答
  • 2020-12-18 23:51

    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

    0 讨论(0)
  • 2020-12-19 00:04

    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.

    0 讨论(0)
  • 2020-12-19 00:09

    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.

    0 讨论(0)
  • 2020-12-19 00:11

    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.

    0 讨论(0)
提交回复
热议问题