16

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));
}
Sumee
  • 377
  • 1
  • 5
  • 12
  • What's wrong with the code you posted? What error you get? – Ondrej Tucny Oct 12 '10 at 12:16
  • 1
    I m confused about whther i should be reading all bytes in one go or not? what are the implications and besides stream.length is long while reader.ReadBytes expects int. – Sumee Oct 12 '10 at 12:22
  • 1
    your question is key - should you be reading all bytes in one go or not? The implication is how much memory you want your process to be using when this chunk of code is called (based on file size, of course). Reading it all in one go could cost a lot of memory. Other answers show how to chunk it up in 1K or 4K bites. If you chunk it, note that it could result in a performance penalty. Those are your trade-offs. Analyze your situation and choose which fits your requirements best. – Jesse C. Slicer Oct 12 '10 at 14:14

8 Answers8

33
    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");
Pavlo Neiman
  • 7,438
  • 3
  • 28
  • 28
  • 3
    Are the BinaryReader and BinaryWriter statements necesarry? – Hong Oct 04 '14 at 01:44
  • Sure you can replace them with "var" – Pavlo Neiman Oct 17 '14 at 08:57
  • 2
    Could you tell me the use of those two statements? In other words, what would happen without these two statements? – Hong Oct 17 '14 at 14:01
  • The File.Copy is so simple! Thank you! – Dov Miller Jul 04 '16 at 13:01
  • I could see the scenario where you would like to get FileStreams open successfully on a set of files before overwriting them. That way you don't have 2 of your 5 files overwritten if you were to use File.Copy. To do that you would need FileStream's open on all the files first, then overwrite them using the filestreams you already opened in conjunction with Binary writer and reader – Terence Apr 18 '17 at 23:04
6

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.

Ali YILDIRIM
  • 156
  • 3
  • 1
    Simple and good for small files. Obviously you wouldn't want to use this for large files, as you'd be loading the entire file content into memory. – contactmatt Mar 08 '17 at 19:08
3

Try something along these lines:

using (FileStream input = File.OpenRead(pathToInputFile),
    output = File.OpenWrite(pathToOutputFile))
{
    int read = -1;
    byte[] buffer = new byte[4096];
    while (read != 0)
    {
        read = input.Read(buffer, 0, buffer.Length);
        output.Write(buffer, 0, read);
    }
}

Note that this is somewhat 'skeletal' and you should amend as required for your application of it.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • Why do u say, i shoould change it as required by my application? Do u mean to say i need to decide the chunk size (which in your case is 4mb)? Should we really read bytes in chunks or can do it in one go? – Sumee Oct 12 '10 at 12:24
  • @Sumee I imagine that the reading it all in one go, is dependent on your filesize, if you have a really massive file, perhaps reading all could be too large for your buffer? (I don't know what happens, other then I suspect you might not get all the text as you expect) – onaclov2000 Oct 12 '10 at 12:28
  • 1
    @Wes Price - sorry i meant 4k – Sumee Oct 12 '10 at 12:31
  • @Summe: Yes, change the file paths and buffer length to what is required. Reading in increments could benefit you, as onaclov2000 mentions, if you have a large file then there are a couple of symptoms which may occur which this approach could help you mitigate. – Grant Thomas Oct 12 '10 at 12:38
  • @Eugene: I believe the offset would be used to specify an offset from the current position in either file, we, however, do not require any further offset as the location we are at in either file is dictated by how many bytes we last read or have written. – Grant Thomas Oct 12 '10 at 12:38
  • @MikeBlandford Oops, fixed, but you know you can edit stuff like that, right? – Grant Thomas May 28 '13 at 15:27
1

Is it necessary to us FileStream? Because you can do this very easily with simple File Class like;

using System.IO;
string FileContent = File.ReadAllText(FilePathWhoseTextYouWantToCopy);
File.WriteAllText(FilePathToWhomYouWantToPasteTheText,FileContent);
KhanZeeshan
  • 1,410
  • 5
  • 23
  • 36
1
using (var inputStream = File.OpenRead(@"C:\file1.txt"))
{
    using (var outputStream = File.OpenWrite(@"D:\file2.txt"))
    {
        int bufferLength = 128;
        byte[] buffer = new byte[bufferLength];
        int bytesRead = 0;

        do
        {
            bytesRead = inputStream.Read(buffer, 0, bufferLength);
            outputStream.Write(buffer, 0, bytesRead);
        }
        while (bytesRead != 0);
    }
}
user472157
  • 146
  • 3
0

If you are not keen at using Read/Write function of File , you can better try using Copy functionality

Easiest will be : 

      File.Copy(source_file_name, destination_file_name, true)

true--> for overwriting existing file,without "true" it will create a new file.But if the file already exists it will throw exception without "true" argument.

Raulp
  • 7,758
  • 20
  • 93
  • 155
0

Use FileStream class, from System.IO.

[ComVisibleAttribute(true)]
public class FileStream : Stream
Svisstack
  • 16,203
  • 6
  • 66
  • 100
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();
ChrisF
  • 134,786
  • 31
  • 255
  • 325