Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Appending text files

Tags:

c#

.net

windows

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();
}
like image 834
Ben Avatar asked Jun 18 '11 17:06

Ben


1 Answers

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);
}
like image 66
Alex Aza Avatar answered Sep 30 '22 00:09

Alex Aza