What actually happens, is that the fileStream2
can not change the subsequent access to a file which already is open for writing (or appending) by fileStream1
.
fileStream2
will successfully open the file leaving a FileShare.Read
as "legacy" for subsequent access only if there are no processes which already have Write
file access to it. Even more, in our example we are talking about the same process. It wouldn't make too much sense to modify a file stream's properties from another file stream, wouldn't it?
Maybe the following comparison explains it even better:
// works
using (var fileStream1 = new FileStream("test.file", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
using (var fileStream2 = new FileStream("test.file", FileMode.Append, FileAccess.Write, FileShare.Read))
using (var fileStream3 = new FileStream("test.file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
}
// fails
using (var fileStream1 = new FileStream("test.file", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
using (var fileStream2 = new FileStream("test.file", FileMode.Append, FileAccess.Write, FileShare.Read))
using (var fileStream3 = new FileStream("test.file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
}
In my opinion, the description phrase for FileShare.Read
:
Allows subsequent opening of the file for reading.
should be read as
The subsequent access to the file is restricted only for reading,
including the access of already existing locks.
[Update]
I haven't parsed through the code, but it seems that these two links could shed some light over the internal functioning of the constructor:
The internal FileStream ctor
The internal FileStream Init method