开发者

Read and append file simultaneously [C#]

I'm looking for a way of opening a file for both reading and appending. FileMode.OpenOrCreate, FileAccess.ReadWrite takes care开发者_运维知识库 only of (over)writing the file and reading, not appending.


Open it with ReadWrite, but seek to the end when you want to write to it. The stream only has a single logical position - if it's at the end, you can't read; if it's in the middle, you'll be overwriting data when you write.

If you're going to be doing a lot of reading and appending, alternating between the two, it may be worth creating a temporary file with all the new data, and then only actually appending it separately when you've finished reading.


The code sample below as per Jon's suggestion:

System.IO.FileStream strm = new FileStream("foo.bar", FileMode.OpenOrCreate, FileAccess.ReadWrite);

strm.Seek(strm.Length, SeekOrigin.End); // <-- Seeking to end of file

Then you can do strm.Write(...) to write to the end of the file.

Hope this helps, Best regards, Tom.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜