I want to append lines to my file. I am using a StreamWriter:
StreamWriter file2 = new StreamWriter(@"c:\file.txt");
file2.WriteLine(someString);
file2.Close();
The output of my file should be several strings below each other, but I have only one row, which is overwritten every time I run this code.
Is there some way to let the StreamWriter append to an existing file?
Replace this:
with this:
true
indicates that it appends text.Replace this line:
with this code:
and then write your line to the text file like this:
Another option is using System.IO.File.AppendText
This is equivalent to the StreamWriter overloads others have given.
Also File.AppendAllText may give a slightly easier interface without having to worry about opening and closing the stream. Though you may need to then worry about putting in your own linebreaks. :)
I assume you are executing all of the above code each time you write something to the file. Each time the stream for the file is opened, its seek pointer is positioned at the beginning so all writes end up overwriting what was there before.
You can solve the problem in two ways: either with the convenient
or by explicitly repositioning the stream pointer yourself:
Actually only Jon's answer (Sep 5 '11 at 9:37) with BaseStream.Seek worked for my case. Thanks Jon! I needed to append lines to a zip archived txt file.