How to write contents of one file to another file?

    using (FileStream stream = File.OpenRead("C:\\file1.txt"))
    using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
    {
        BinaryReader reader = new BinaryReader(stream);
        BinaryWriter writer = new BinaryWriter(writeStream);

        // create a buffer to hold the bytes 
        byte[] buffer = new Byte[1024];
        int bytesRead;

        // while the read method returns bytes
        // keep writing them to the output stream
        while ((bytesRead =
                stream.Read(buffer, 0, 1024)) > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
        }
    }

Just wonder why not to use this:

File.Copy("C:\\file1.txt", "D:\\file2.txt");

You should be using File.Copy unless you want to append to the second file.

If you want to append you can still use the File class.

string content = File.ReadAllText("C:\\file1.txt");
File.AppendAllText("D:\\file2.txt",content);

This works for file with small size as entire file in loaded into the memory.

Tags:

C#

.Net