C#: Appending *contents* of one text file to another text file
c#, file-io
Solution
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);
}
}
}
Problem
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!