190

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?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Waypoint
  • 17,283
  • 39
  • 116
  • 170

11 Answers11

318

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);
DWRoelands
  • 4,878
  • 4
  • 29
  • 42
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • Append works great. For my purposes I needed to add a header row (1st line in the file) if the file doesn't exist. If you need to know if the file was newly created (no data), you can test for swObject.BaseStream.Position=0. – gritware Nov 10 '22 at 19:13
155
 using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
 using (StreamWriter sw = new StreamWriter(fs))
 {
    sw.WriteLine(something);
 }
Andrey Taptunov
  • 9,367
  • 5
  • 31
  • 44
16

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);
Jon
  • 428,835
  • 81
  • 738
  • 806
  • what if the file has 10mb and I start writing from position 0, but only 10kb, how can I assure that the file *only* contains the 10kb data I've just written? – JobaDiniz Oct 11 '17 at 17:58
10

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();
Marco
  • 56,740
  • 14
  • 129
  • 152
7

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.

using (FileStream zipFS = new FileStream(@"c:\Temp\SFImport\test.zip",FileMode.OpenOrCreate))
{
    using (ZipArchive arch = new ZipArchive(zipFS,ZipArchiveMode.Update))
    {
        ZipArchiveEntry entry = arch.GetEntry("testfile.txt");
        if (entry == null)
        {
            entry = arch.CreateEntry("testfile.txt");
        }
        using (StreamWriter sw = new StreamWriter(entry.Open()))
        {
            sw.BaseStream.Seek(0,SeekOrigin.End);
            sw.WriteLine("text content");
        }
    }
}
7

Replace this:

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

with this:

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

true indicates that it appends text.

Cullub
  • 2,901
  • 3
  • 30
  • 47
Waqas
  • 6,812
  • 2
  • 33
  • 50
5

Use this StreamWriter constructor with 2nd parameter - true.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
5

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. :)

Chris
  • 27,210
  • 6
  • 71
  • 92
3

One more simple way is using the File.AppendText it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter

using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{                                                
    sw.WriteLine("this is a log");
}
Vinod Srivastav
  • 3,644
  • 1
  • 27
  • 40
1

Replace this line:

StreamWriter sw = new StreamWriter("c:/file.txt");

with this code:

StreamWriter sw = File.AppendText("c:/file.txt");

and then write your line to the text file like this:

sw.WriteLine("text content");
Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
Shahaf
  • 11
  • 1
1

You can use like this

 using (System.IO.StreamWriter file =new System.IO.StreamWriter(FilePath,true))
             {
                    
                    
            `file.Write("SOme Text TO Write" + Environment.NewLine);         
                    
             }