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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…