Reading bytes from disk.

  • Thread starter Thread starter Michael S
  • Start date Start date
M

Michael S

Hi!

I've seen several different methods for reading and writing.

Could someone help me with an example showing the best way (regarding
performance) to read a binary file from disk, keep it memory as a bytearray
and later write the binary file to disk.

Thanks
- Michael S
 
Hi Michael,

Seeing as noone else responded yet, I'll give it a try. I am not sure if there are any faster ways but as long as you read from a local disk this code should work. If you read over a network using TCP/IP and similar, you need to read in chunks and take into account that the chunk may be any size.

// read a file into a byte array
FileStream fs = File.Open("c:\\file.bin", FileMode.Open);
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
fs.Close();

// write a byte array to file
FileStream fs = File.Create("c:\\file2.bin");
fs.Write(b, 0, b.Length);
fs.Close();
 
Morten Wennevik said:
Seeing as noone else responded yet, I'll give it a try. I am not sure
if there are any faster ways but as long as you read from a local
disk this code should work. If you read over a network using TCP/IP
and similar, you need to read in chunks and take into account that
the chunk may be any size.

// read a file into a byte array
FileStream fs = File.Open("c:\\file.bin", FileMode.Open);
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
fs.Close();

// write a byte array to file
FileStream fs = File.Create("c:\\file2.bin");
fs.Write(b, 0, b.Length);
fs.Close();

I odn't believe there's any guarantee that that will work - streams in
general don't guarantee that they will read the amount you ask them to
in a single chunk. See
http://www.pobox.com/~skeet/csharp/readbinary.html for more
information.

You should also use a using statement with the stream so that it will
be disposed of whether or not an exception occurs.
 
Back
Top