How can I open a FileStream, read the file contents, and then write (append) to file without re-opening the file?
A problem with StreamReader/StreamWriter in this case is they assume ownwership of the underlying stream. Since the target is .NET 4 the "leaveOpen" constructor overloads cannot be used. (I don't care if StreamReader/StreamWriter are used - but they do provide ReadLine and WriteLine operations.)
In summary, example of problematic code related to the question and how the application will access and manage the lifetime of the FileStream (that is to be opened once):
var fs = File.Open(..);
using (var reader = new StreamReader(fs)) {
// Do all reading here, then ditch the reader
} // .. but StreamReader will Close the FileStream
SeekToEnd(fs);
using (var writer = new StreamWriter(fs)) {
// Do all writing here, then ditch the writer
// .. ideal, but FileStream already Closed
}
// Finally, somewhere else:
fs.Close();
The "relevant" MSDN articles I have found always show this as two separate steps: this question is about doing the read-then-write operation of Text in a Line-oriented manner without opening the file twice.
The file is opened as
File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)
and the underlying stream will always be seek-able and write-able.
You be able to just set the position of the stream to the end of the stream and write from there
fs.Position = fs.Length;
//then do the write operations you need to do
Even if you are using a stream writer or reader you should be able to modify the FileStream that the reader/writer is consuming, which would allow you to read then write
using(var fs = File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)
{
using(var reader = new TextReader(fs))
using(var writer = new TextWriter(fs))
{
//read
fs.Position = fs.Length;
//write
}
}