No, there still isn't a way to do that without using try ... catch
, and if I were you I wouldn't hold my breath waiting for one.
What you're really asking for is a group of functions that can tell you whether or not an attempt to open a file in a particular mode will succeed. Something like a File.CanOpenForExclusiveRead()
or something similar. There are no such methods in .NET, and they don't exist in the Windows API. And for good reason.
Let's say that such a function existed. That is, you could write:
if (File.CanOpenForExclusiveRead(filename))
{
f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);
}
Sounds like a good idea, right? Except you'd still need to put a try ... catch
around the FileStream
constructor because some other thread (perhaps in another process) might open the file for exclusive read between the time your code checked and the time your code called the constructor. Or something else could go wrong: the file could be deleted, the disk could go offline, etc.
To be sure, that fictional File.CanOpenForExclusiveRead
method would be useful in some cases. Those cases, though, are few and far between, and as I showed above they wouldn't do you a whole lot of good anyway, since you'd still have to handle possible exceptions anyway.
If you want a method that does that, write your own that uses try ... catch
and returns false
if an exception is thrown. At least then you hide the details of the implementation. But don't wait for a better solution. It's highly unlikely that one is forthcoming.