Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a byte array and MemoryStream

I am reading a binary file into a parsing program. I will need to iterate through the file and look for certain markers so I can split the file up and pass those parts into their respective object’s constructors.

Is there an advantage to holding the file as a stream, either MemoryStream or FileStream, or should it be converted into a byte[] array?

Keith

like image 459
Keith Sirmons Avatar asked Aug 19 '08 20:08

Keith Sirmons


People also ask

Does MemoryStream copy byte array?

From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.

What is a MemoryStream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

What is the difference between byte [] and stream?

The main difference between Byte Stream and Character Stream in Java is that Byte Stream helps to perform input and output operations of 8-bit bytes while Character stream helps to perform input and output operations of 16-bit Unicode.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.


2 Answers

A byte[] or MemoryStream will both require bringing the entire file into memory. A MemoryStream is really a wrapper around an underlying byte array. The best approach is to have two FileStream (one for input and one for output). Read from the input stream looking for the pattern used to indicate the file should be separated while writing to the current output file.

You may want to consider wrapping the input and output files in a BinaryReader and BinaryWriter respectively if they add value to your scenario.

like image 187
denis phillips Avatar answered Sep 30 '22 10:09

denis phillips


A MemoryStream is basically a byte array with a stream interface, e.g. sequential reading/writing and the concept of a current position.

like image 29
Timbo Avatar answered Sep 30 '22 10:09

Timbo