Can one check if File is Locked without Try..Catch..Finally?

Mike_R

Well-known member
Joined
Oct 20, 2003
Messages
316
Location
NYC
Hi guys,

I was wondering how one might test if a File is Locked without resorting to a Try..Catch..Finally block. Im not sure if it can be done, but I was thinking that it *should* be doable? Using a T/C/F block we can do something like this:
Code:
Shared Function FileIsLocked(ByVal fileFullPathName As String) As Boolean
    Dim isLocked As Boolean = False
    Dim fileObj As System.IO.FileStream

    Try
        fileObj = New System.IO.FileStream( _
                                fileFullPathName, _
                                System.IO.FileMode.Open, _
                                System.IO.FileAccess.ReadWrite, _
                                System.IO.FileShare.None)
    Catch
        isLocked = True
    Finally
        If fileObj IsNot Nothing Then
            fileObj.Close()
        End If
    End Try

    Return isLocked
End Function
Any thoughts on if/how this could be done without a T/C/F block? (On the other hand, this ran surprisingly fast, Im not sure why... So its not really *that* improtant, but I was curious if anyone had some other thoughts on this...)

Thanks in advance!
Mike
 
Technically you are just detecting if the file can be opened or not - security, network issues etc would all cause your function to report the file is locked...

Also you need to be aware of checking if a file is accesible and then trying to open it as on a multi-tasking OS like windows something could happen to the file inbetween you checking and then opening it.
 
Hi, thinks PD, you make two excellent points:

PlausiblyDamp said:
Technically you are just detecting if the file can be opened or not - security, network issues etc would all cause your function to report the file is locked...
Yes, I was aware of this... Technically, I guess the order is (a) Check if File Exists, (b) Check if have Access/Permissioning, (c) Check if the file is Open/Locked. I was not real concerned with the 1st two steps, at the moment...

Also you need to be aware of checking if a file is accesible and then trying to open it as on a multi-tasking OS like windows something could happen to the file inbetween you checking and then opening it.
Ok, this is something that I had not thought of... So the only *real* approach then is to simply try to open whatever it is you wish to open and trap any errors with Try..Catch..Finally. Otherwise, there is a minute risk of a problem. Good pickup!

Thanks PD. :)
 
Ive been caught out by thinking too hard myself in the past, sometimes its just easier to try it and handle the errors that are raised rather than check for all the possible error cases first.

As a caveat though - exceptions can be a bit expensive in performance terms - if there is going to be lots of file IO and a high percentage will fail then an alternate method may be better.
 
Ah yes, well your caveat (your 2nd point above) is why I was looking for a non Try..Catch..Finally approach in the first place. I was hoping that something along the lines of checking the FileStream.CanWrite property could to the trick... However, the New FileStream() constructor simply fails in the first place if the file is locked, sending me back to the Try..Catch..Finally approach.

On the other hand, I was shocked at how quickly this particular error seems to be thrown and caught. Maybe Im insane, but this one seems to run lightening-fast compared to the roughly 0.5 seconds delay I get with other errors that are thrown-caught. This one seem instantaneous (to the human eye anyway), so my initial concern is essentially very small...
 
The first exception thrown by an application tends to be very slow, depending on the PC and circumstances it can actually take seconds.

All subsequent exceptions are actually handled pretty quickly. This surprises plenty of people because throwing exceptions is, according to documentation, a very slow process. The reality is, though, that it is all relative. If you throw exceptions frequently on a tight loop, the hit will be enormous. In your case, though, they might not even be noticeable. (Not that I advise anything except avoiding exceptions when possible--their speed is not something to depend on and exceptions are one thing that it is important to use for its specified purpose.)
 
Thanks Marble, this is very good info. I was not at all aware of this, and had been generally appalled at the time required to throw-and-catch an exception, since I usually got times of about 0.4 to 0.5 secs.

But after testing the 1st vs. subsequent exceptions, it is clear that you are very correct. The first exception can vary all over the map, but I get anywhere from 5 ms to 15 ms when run as an EXE, and up to 500 ms (a full half second) when thrown-caught from within the IDE in debug mode.

However, the 2nd and subsequent exceptions seem to be at about 0.3 ms when run as a compiled EXE, which is pretty manageable in most cases. Yes, you would not even want this kind of a hit in a tight loop, but this is not generally worth panicking about. (My PC has an AMD 2800 chip, just for reference.)

I tested the same with COM Exception handling, just for kicks, and its about 10x slower at around 3.0 ms per exception thrown-caught. This is heavier, but even this is still not a disaster.

Very good food for thought,
Thanks a ton ME :),
Mike
 
Back
Top