Ben
Ben

Reputation: 341

C# - Appending text files

I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)

private static void Ignore()
{
    System.IO.StreamReader myFile =
       new System.IO.StreamReader("c:\\test.txt");
    string myString = myFile.ReadToEnd();

    myFile.Close();
    Console.WriteLine(myString);

    // Write the string to a file.
    System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
    file.WriteLine(myString);

    file.Close();
}

Upvotes: 11

Views: 31521

Answers (4)

Alex Aza
Alex Aza

Reputation: 78507

If the file is small, you can read and write in two code lines.

var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);

If the file is huge, you can read and write line-by-line:

using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
    var line = source.ReadLine();
    destination.WriteLine(line);
}

Upvotes: 18

BrokenGlass
BrokenGlass

Reputation: 161002

using(StreamWriter file = File.AppendText(@"c:\test2.txt"))
{
    file.WriteLine(myString);
}

Upvotes: 9

BugFinder
BugFinder

Reputation: 17868

Try

StreamWriter writer = File.AppendText("C:\\test.txt");
writer.WriteLine(mystring);

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

Use File.AppendAllText

File.AppendAllText("c:\\test2.txt", myString)

Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.

Upvotes: 6

Related Questions