Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Appending *contents* of one text file to another text file

Tags:

c#

file-io

There is probably no other way to do this, but is there a way to append the contents of one text file into another text file, while clearing the first after the move?

The only way I know is to just use a reader and writer, which seems inefficient for large files...

Thanks!

like image 637
CODe Avatar asked Feb 23 '11 19:02

CODe


2 Answers

No, I don't think there's anything which does this.

If the two files use the same encoding and you don't need to verify that they're valid, you can treat them as binary files, e.g.

using (Stream input = File.OpenRead("file1.txt"))
using (Stream output = new FileStream("file2.txt", FileMode.Append,
                                      FileAccess.Write, FileShare.None))
{
    input.CopyTo(output); // Using .NET 4
}
File.Delete("file1.txt");

Note that if file1.txt contains a byte order mark, you should skip past this first to avoid having it in the middle of file2.txt.

If you're not using .NET 4 you can write your own equivalent of Stream.CopyTo... even with an extension method to make the hand-over seamless:

public static class StreamExtensions
{
    public static void CopyTo(this Stream input, Stream output)
    {
        if (input == null)
        {
            throw new ArgumentNullException("input");
        }
        if (output == null)
        {
            throw new ArgumentNullException("output");
        }
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
    }
}
like image 86
Jon Skeet Avatar answered Oct 19 '22 00:10

Jon Skeet


Ignoring error handling, encodings, and efficiency for the moment, something like this would probably work (but I haven't tested it)

File.AppendAllText("path/to/destination/file", File.ReadAllText("path/to/source/file"));

Then you just have to delete or clear out the first file once this step is complete.

like image 21
Marty Avatar answered Oct 19 '22 01:10

Marty