File.ReadAllBytes
This C# method returns a byte
array. ReadAllBytes()
is simple to call—it receives a file name and returns the file data.
This method can be combined with other types to create high performance file formats. We can use this method to implement an in-memory data representation.
We see the syntax for calling File.ReadAllBytes
. The method returns a byte
array, which will be stored in the large object heap if it is large.
byte
array. With ReadAllBytes()
, we get a byte
array from a file.using System; using System.IO; class Program { static void Main() { byte[] array = File.ReadAllBytes("C:\\a"); Console.WriteLine("First byte: {0}", array[0]); Console.WriteLine("Last byte: {0}", array[array.Length - 1]); Console.WriteLine(array.Length); } }First byte: 29 Last byte: 0 5407219
ReadAllBytes()
uses the using
-statement on a FileStream
. Then it loops through the file and puts the bytes into an array. It throws an exception if the file exceeds 2 gigabytes.
After using ReadAllBytes
, you can use MemoryStream
and BinaryReader
to read in a binary file you had previously generated with BinaryWriter
. This yields fast file formats.
ReadAllBytes
loads a binary file into memory. It has a simple calling pattern and is implemented in a straightforward and efficient way.