Append lines to a file using a StreamWriter
Asked Answered
S

11

193

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?

Sills answered 5/9, 2011 at 9:32 Comment(4)
Don't forget to dispose StreamWriter . A using block is better syntax for this.Bharat
This is also why I prefer not to worry about streams when doing very quick updates to a file by using File.AppendAllText - msdn.microsoft.com/en-us/library/ms143356.aspxPhysician
@Bharat - Can you show me some code to do that ?Whithersoever
@blasto using (var stream = new StreamWriter(..)) { stream.WriteLine(..); }Bharat
M
320

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);
Monthly answered 5/9, 2011 at 9:35 Comment(1)
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.Polio
D
157
 using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
 using (StreamWriter sw = new StreamWriter(fs))
 {
    sw.WriteLine(something);
 }
Division answered 5/9, 2011 at 9:36 Comment(0)
B
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);
Bebe answered 5/9, 2011 at 9:37 Comment(1)
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?Flyer
E
11

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();
Englert answered 5/9, 2011 at 9:37 Comment(0)
B
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.

Boil answered 5/9, 2011 at 9:35 Comment(0)
P
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");
        }
    }
}
Placket answered 12/5, 2015 at 7:49 Comment(1)
You should use a FileStream before using a StreamWriter and specify options for appending. Then there is no need to .Seek() because the content will be appended at the end of the file.Frenchify
B
5

Use this StreamWriter constructor with 2nd parameter - true.

Buckbuckaroo answered 5/9, 2011 at 9:36 Comment(0)
P
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. :)

Physician answered 5/9, 2011 at 9:41 Comment(0)
A
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");
}
Albrecht answered 30/12, 2016 at 12:28 Comment(0)
F
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");
Froude answered 22/12, 2015 at 8:56 Comment(0)
F
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);         
                    
             }
        
Faveolate answered 11/8, 2020 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.