System.IO.FileStream FileAccess vs FileShare

FileAccess says what you are going to do with the file. Pretty easy to understand, you’ll know you are going to read or write.

FileShare is the much trickier one since it requires you to step into the shoes of another programmer. It determines what another process can do if it also has the file opened. Two processes accessing a file can be very troublesome, you’ll need to reason through the possible failure modes. The value you pick is strongly correlated to the type of the file and the access you want. Breaking it down by what you are going to do:

FileAccess.Read

There is never any trouble if another process also reads from the file. So FileShare.Read is the default choice.

You may need FileShare.ReadWrite if another process has already opened the file for writing. It already gained write access so you can never open the file yourself with just FileShare.Read, you can’t deny writing since that other process was first, you’ll be denied access instead. This generally only comes to a good on a text file, the kind where you can be sure that the other process is only ever appending text to the end of the file. A log file is the very common scenario. Still possibly tricky, it matters exactly when that process flushes changes to the file. You might observe partially written lines of text, beware of this.

FileAccess.Write

You cannot use FileShare.Write or FileShare.ReadWrite. Since that would allow two processes writing to the file at the same time, the file content will be a jumble of output from both programs. A possible workaround is these processes arbitrating access to the file, ensuring only one of them can ever access the file at the same time. Normally implemented by a named mutex.

You can use FileShare.Read if it is text file, same scenario I described above with the log file. The default choice otherwise should be FileShare.None

FileAcces.ReadWrite

Not that common, only used if you write binary data and use Seek(). There is no hope that any other process could ever read the file correctly while you are doing this, assuming they don’t arbitrate access themselves, you must use FileShare.None.

Leave a Comment