Append lines to a file using a StreamWriter

Solution 1:

Use this instead:

new StreamWriter("c:\\file.txt", true);

With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.

C# 4 and above offers the following syntax, which some find more readable:

new StreamWriter("c:\\file.txt", append: true);

Solution 2:

 using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
 using (StreamWriter sw = new StreamWriter(fs))
 {
    sw.WriteLine(something);
 }

Solution 3:

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

file2 = new StreamWriter("c:/file.txt", true);

or by explicitly repositioning the stream pointer yourself:

file2 = new StreamWriter("c:/file.txt");
file2.BaseStream.Seek(0, SeekOrigin.End);