Willy,
The OP is trying to handle business logic depending on whether or not
the file is in use. When coding business logic, flow control, IMO, should
never be predicated on exception handling, especially when there is a way to
check the status.
Of course, this is a matter of preference. If other people want to base
their logic on exception handling, they are free to do so, but I think there
is a strong camp that disagrees with this approach.
Also, the OP specifically asked for a solution that did not involve
using exceptions to determine if the file was in use.
From a performance standpoint, I think that the seven or so extra
instructions to call API through the P/Invoke layer (which are going to be
called anyways by the constructor if you didn't pass in a file handle) are a
small price to pay as opposed to throwing an exception.
You are right about the constructor being marked as obsolete and passing
a SafeHandle. I didn't mention it because I assume that most people are not
using the beta, but the OP should know that as well.
--
- Nicholas Paldino [.NET/C# MVP]
-
(E-Mail Removed)
"Willy Denoyette [MVP]" <(E-Mail Removed)> wrote in message
news:%(E-Mail Removed)...
>
> "Nicholas Paldino [.NET/C# MVP]" <(E-Mail Removed)> wrote
> in message news:(E-Mail Removed)...
>> Gabe,
>>
>> Instead of doing that, I would recommend declaring the CreateFile API
>> function so that you can call it through the P/Invoke layer. The
>> CreateFile function will return an error code if you can not access the
>> file, which is much cleaner than handling the exception.
>>
>> Once you have that, if you are able to open the file with the
>> CreateFile API, then you can pass the handle to the FileStream
>> constructor, which takes a file handle.
>>
>> Hope this helps.
>>
>
> Sorry to ask, but why do you thing it's much cleaner to PInvoke instead of
> handling the exception?
> You have to test the return value of CreateFile, and only retry the call
> if the file is in use, but you have to test for other error conditions too
> and take appropriate actions (throw or ..). IMO when all is done
> (correctly )you will have coded a great deal of what's been done in
> File.OpenRead.
>
> Note also that v2's FileStream constructors that accept an IntPtr as
> handle are deprecated, so you will have to encapsulate the handle returned
> in a SafeHandle before passing to the FileStream ctor.
>
>
> Willy.
>
>
>