Alex Rivera | Logout

How to write contents of one file to another file?

Asked 2010-10-12T12:05:20.127
17

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));
}
Edit
Report

2 Answers

0

Use FileStream class, from System.IO.

[ComVisibleAttribute(true)]
public class FileStream : Stream
answered 2010-10-12T12:06:21.953
0

Have you checked that the reader is reading all the data? This MSDN page has an example that checks all the data is read:

    byte[] verifyArray = binReader.ReadBytes(arrayLength);
    if(verifyArray.Length != arrayLength)
    {
        Console.WriteLine("Error reading the data.");
        return;
    }

The other alternative is that you probably need to Flush the output buffer:

writer.Flush();
answered 2010-10-12T12:24:54.530

Your Answer