Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write contents of one file to another file?

Tags:

c#

.net

I need to write contents of a file to another file using File.OpenRead and File.OpenWrite methods. I am unable to figure out how to do it.

How can i modify the following code to work for me.

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);
       writer.Write(reader.ReadBytes(stream.Length));
}
like image 532
Sumee Avatar asked Oct 12 '10 12:10

Sumee


2 Answers

    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");
like image 94
Pavlo Neiman Avatar answered Nov 02 '22 19:11

Pavlo Neiman


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.

like image 38
Ali YILDIRIM Avatar answered Nov 02 '22 21:11

Ali YILDIRIM