Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c# - Append access can be requested only in write-only mode

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?

question from:https://stackoverflow.com/questions/65924978/append-access-can-be-requested-only-in-write-only-mode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...