views:

1348

answers:

1

Is there a better way to check if a file is not locked then to open the file to catch an exception. I have a filewatcher running on a directory and I need to do something to the file after the file has completely moved/created in the location. Aren't throwing an exception a performance hit? Is there a better way?

Private Function FileAvailable(ByVal fileName As String) As Boolean
    Try
        Using inputStream As FileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)
            Return True
        End Using
    Catch ex As IOException
        Return False
    End Try
End Function

or

private bool FileAvailable(string fileName) { 
try { 
    using (FileStream inputStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { 
        return true; 
    } 
} 
catch (IOException ex) { 
    return false; 
}

}

A little expert advise on the best way. Thanks

The file is being copied into the watch directory. No other user has access to the directory. I just need to verify that the file is completly copied into the directory berfore I process and move the file myself. I need exclusive access to it.

+6  A: 

Just how often are you going to be doing this? To put it in context, suppose you check once every 50 milliseconds - which is pretty frequently. My laptop (last time I checked) was able to throw over 100 exceptions per millisecond... so the cost of throwing the exception would be less than 0.02% of the overall time - and that's assuming it's always busy!

Now, it would certainly be nice to have an API to avoid this - a sort of TryOpenFile - but in its absence, I'd just tuck it away in another function and not worry.

Bear in mind, however, that if you're just returning a Boolean then your data is stale as soon as it's returned - another process could grab an exclusive lock as soon as you've returned "it's okay." To avoid that, you should consider returning the open stream instead.

Jon Skeet
I wonder if the only way to lock a file is to open it.
Rauhotz
The race condition Jon mentions mens you have to do this anyway, so just do it directly with a TryOpenFile if the consumer doesn't wan to have to know which Exceptions to deal with (this is a criminal error of the IOException model, there should be a FileLockedException)
ShuggyCoUk