Usage of the FileShare enumeration on Windows
2009年8月24日
Usage of the FileShare enumeration on Windows
Robbie Mosaic Fan
In Microsoft .NET class library, there is a FileShare enumeration. If you use
the FileStream constructor to create a FileStream object, you can use the
FileShare enumeration to specify share mode for the file. There are several
members: Delete, Inheritable, None, Read, ReadWrite and Write. In this article
I’m going to talk about three most basic members: Read, ReadWrite and Write.
the FileStream constructor to create a FileStream object, you can use the
FileShare enumeration to specify share mode for the file. There are several
members: Delete, Inheritable, None, Read, ReadWrite and Write. In this article
I’m going to talk about three most basic members: Read, ReadWrite and Write.
The rule is simple: for a file to be shared between two processes, each process
should give the other enough FileShare rights.
should give the other enough FileShare rights.
Let’s use two processes as an example. Process A and Process B. If A opens a
file for reading, and B then opens the same file for writing, in which
situation will both operations succeed? Because A is reading, B must open the
file with at least FileShare.Read. It can also open the file with
FileShare.ReadWrite, which includes FileShare.Read. However, for process B to
succeed, it also requires A to open the file with at least FileShare.Write.
file for reading, and B then opens the same file for writing, in which
situation will both operations succeed? Because A is reading, B must open the
file with at least FileShare.Read. It can also open the file with
FileShare.ReadWrite, which includes FileShare.Read. However, for process B to
succeed, it also requires A to open the file with at least FileShare.Write.
What if B opens the file with read and write, that is, FileAccess.ReadWrite?
Then following the rule discribed above, A must use FileShare.ReadWrite.
Then following the rule discribed above, A must use FileShare.ReadWrite.
Just that simple.