-2

HI can any one help me how to read from text file and append those in another text file.

File 1
line1
line2
line3

file2
line4
H H
  • 263,252
  • 30
  • 330
  • 514
Siddharth
  • 3
  • 3
  • 6
    Well, what have you tried so far? (Hint: you can do this with two method calls using the `File` class...) – Jon Skeet Jun 02 '15 at 17:54
  • Welcome to stackoverflow. Please read [ask]. And msdn on system.io.file. – Zohar Peled Jun 02 '15 at 17:57
  • I'm voting to close this question as off-topic because the question does not show any effort before asking the community for help. – Eric J. Jun 02 '15 at 17:58
  • `var secondContent = File.ReadAllText("second_file_name"); File.AppendAllText("main_file_name", secondContent);` – rnofenko Jun 02 '15 at 17:58
  • Thanks! done with the file class.and just wanted to know whether the file when appending can be created with the duplicate data, which we have already copied!. – Siddharth Jun 04 '15 at 21:37

1 Answers1

0

This is a general solution that minimizes memory consumption which is good for working with very large files.

using(var writer = File.AppendText(@"path\to\file2.txt"))
{
    foreach(var line in File.ReadLines(@"path\to\file.txt"))
    {
        writer.WriteLine(line);
    }
}

See also File.AppendText.

Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • 1
    This can be further reduced to: `File.AppendAllText(@"path\to\file2.txt", File.ReadAllText(@"path\to\file1.txt"));`, the foreach isn't really necessary in this case. – Ron Beyer Jun 02 '15 at 18:05
  • That works well for small files, but memory consumption grows with file size. – Dustin Kingen Jun 02 '15 at 18:15