Append access can be requested only in write-only mode

Viewed 482

I need to be able to read from a file that's also open for writing, and furthermore, I need to open the writable file for Append, because it can be very large and I only need to add to it. So I have this code:

var file = @"...";

var fsWrite = new FileStream(file, FileMode.Append, FileAccess.ReadWrite, FileShare.ReadWrite);
var writer = new SmartWaveFileWriter(fsWrite, WaveInfo.WatsonWaveFormat);

var fsRead = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
var reader = new SmartWaveFileReader(fsRead);

reader.Dispose();
fsRead.Dispose();

writer.Dispose();
fsWrite.Dispose();

This fails with System.ArgumentException: Append access can be requested only in write-only mode.

If instead of FileMode.Append, I use FileMode.OpenOrCreate, I get no errors, but the contents of the file are lost.

How can I accomplish append but also be able to open the file for sharing like this?

1 Answers

How can I accomplish append but also be able to open the file for sharing like this?

Don't confuse "access" with "share". The FileAccess enum describes how your process wants to use the file. The FileShare enum describes what other handles to the file (including those in your own process) can do with the file.

In your case, you need to change new FileStream(file, FileMode.Append, FileAccess.ReadWrite, FileShare.ReadWrite) to new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.Read) and change new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite) to new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite).

Technically, you could get away with leaving the FileShare values as-is, but one really shouldn't have more than one writer to the file, and from the way your question is worded it seems like that's not what you want anyway. So in the above, I've changed the writer to share only as FileShare.Read, and the reader to open the file only with FileAccess.Read, in addition to fixing the incorrect FileAccess.ReadWrite for the writer as the exception message indicates is needed.

Related