John said:
What is the most efficient technique to read a binary file ( such as a
.dll or .exe ) into a byte[] ?
Are there advantages to using a BinaryReader ?
BinaryReader is mainly useful for when you are dealing with specific data
types _other_ than an array of bytes.
As for "the most efficient technique" for reading a binary file, it all
depends. But, depending on your needs, your first try should be simply to
allocate a byte[] of the necessary size, and then make a single call to
FileStream.Read() to read all of the data at once.
For absolute correctness, you should actually code that as a loop,
checking the return value of Read() and calling it again to read any
remaining bytes if the return value is less than the total length
remaining to read.
But for a FileStream, the complete file _should_ be always read in a
single call to Read().
Doing it this way delegates all of the buffering and data copying tasks to
.NET and Windows. Most of the time, those components will be able to do
the i/o as efficiently as possible. If you have some specific need or
consideration that requires a different strategy, you should be specific
about that so you can receive advice specific to that need or
consideration.
Finally, note that with respect to file i/o, unless you are accessing the
same file repeatedly, it's unlikely that anything you do in your code will
very much affect the over throughput, because the real bottleneck is
simply in getting the data from the storage device.
Pete