MaPo
MaPo

Reputation: 3

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.

Upvotes: 0

Views: 856

Answers (2)

t0mm13b
t0mm13b

Reputation: 34592

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500875

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.

Upvotes: 6

Related Questions