11

How do I read a raw byte array from any file, and write that byte array back into a new file?

Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607
  • 5
    Encoding & BinaryWriter? Encoding is a "string" thingy. You shouldn't have a problem when you are dealing with binary data. – Mehrdad Afshari Sep 20 '09 at 07:49
  • Jeremy, do you mean "depending on the file type the *format* varies..." ? if the code you're using tries to read/write files with the wrong file type/format I'm sure there would be corruption. – pavium Sep 20 '09 at 07:58
  • 3
    Reading a file as a `byte[]` is not necessarily a good idea; this could be **very** expensive for large files. – Marc Gravell Sep 20 '09 at 08:23

4 Answers4

7

(edit: note that the question changed; it didn't mention byte[] initially; see revision 1)

Well, File.Copy leaps to mind; but otherwise this sounds like a Stream scenario:

    using (Stream source = File.OpenRead(inPath))
    using (Stream dest = File.Create(outPath)) {
        byte[] buffer = new byte[2048]; // pick size
        int bytesRead;
        while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
            dest.Write(buffer, 0, bytesRead);
        }
    }
Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5
byte[] data = File.ReadAllBytes(path1);
File.WriteAllBytes(path2, data);
Tommy Carlier
  • 7,951
  • 3
  • 26
  • 43
3

Do you know about TextReader and TextWriter, and their descendents StreamReader and StreamWriter? I think these will solve your problem because they handle encodings, BinaryReader does not know about encodings or even text, it is only concerned with bytes.

How to read text from a file

How to write text to a file

This is an excellent intro to file IO and encodings.

Dale
  • 12,884
  • 8
  • 53
  • 83
0

Adding an up to date answer,

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        source.CopyTo(dest);
    }
}

you can optionally specify the buffer size

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        source.CopyTo(dest, 2048); // or something bigger.
    }
}

or you could perform the operation on another thread,

using (var source = File.OpenRead(inPath))
{
    using (var dest = File.Create(outPath))
    {
        await source.CopyToAsync(dest);
    }
}

which would be useful when the main thread has to do other work, like with WPF and Windows Store apps.

Jodrell
  • 34,946
  • 5
  • 87
  • 124