I have to disagree with the "greater support issue part". Calling a
function through the P/Invoke layer, for the most part, is not that big of
a deal. That's a matter of opinion, and I'm willing to accept that people
have different takes on how much of a support issue, or how difficult
using the P/Invoke layer is.
In this case, however, the fundamental difference between approaches is
that yours allows for the error that can occur in the time it takes to try
and open the file and get the exception, and to call CreateFile to
determine if it is a sharing violation. With your approach, there is a
window of opportunity that introduces the possibility that the reason for
the IOException can change, whereas mine does not. If you call CreateFile
first, and it fails, you have the reason for your failure, and you can
process the error code from there (which you can end up generating a
FileLoadException for, which derives from IOException).
If the call to CreateFile succeeds, then you have the handle to the
file, and you can pass it along to the FileStream constructor, with no
gaps in your hold on the file, and eliminating the possibility of that
very unlikely, and subtle bug.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Larry Smith said:
There are pros and cons to all techniques. While it ultimately boils down
to a personal judgment call, the big issue that jumps out at me with the
above suggestion is that it's usually unnecessary. Why resort to a Win32
function like "CreateFile()" when sharing violations don't occur that
frequently in practice (though I can't speak for the op's runtime
enviornment but it's likely the same). The way I suggested defers calling
it unless you have to (infrequently). And even then it's only to check
for a sharing violation (a necessary evil), not to actually create the
handle for passing to "FileStream". While your approach might circumvent
the exception, it involves a greater mixing of Win32 and .NET IMO. It's
more "in your face" IOW and a greater support issue which is best avoided
in this case (IMHO).