Reputation: 153
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.
Upvotes: 1
Views: 4783
Reputation: 1499860
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.
Upvotes: 8