181

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
  • 139,522
  • 20
  • 204
  • 252
Waypoint
  • 16,445
  • 37
  • 114
  • 168

11 Answers11

299

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,785
  • 4
  • 26
  • 40
Øyvind Bråthen
  • 56,684
  • 27
  • 122
  • 146
152
 using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
 using (StreamWriter sw = new StreamWriter(fs))
 {
    sw.WriteLine(something);
 }
Andrey Taptunov
  • 9,187
  • 5
  • 30
  • 43
14

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
  • 413,451
  • 75
  • 717
  • 787
  • 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
  • 55,302
  • 13
  • 128
  • 150
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,603
  • 2
  • 26
  • 46
Waqas
  • 6,740
  • 2
  • 30
  • 44
5

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");
        }
    }
}
5

Use this StreamWriter constructor with 2nd parameter - true.

Kirill Polishchuk
  • 52,773
  • 10
  • 120
  • 121
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
  • 26,664
  • 5
  • 69
  • 88
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,066
  • 1
  • 23
  • 34
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,617
  • 1
  • 28
  • 48
Shahaf
  • 11
  • 1
0

You can use like this

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