C# File.ReadAllBytes, Get Byte Array From File

This C# example program shows the File.ReadAllBytes method in System.IO. It gets a byte array from a file.
File.ReadAllBytes returns a byte array. It is simple to call—it receives a filename and returns the file data. It can be combined with other types to create high performance file formats.Byte Array
Example. 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. The array can of course be used as any other byte[] type. We get a byte array from a file.
C# program that uses File.ReadAllBytes method 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); } } Output First byte: 29 Last byte: 0 5407219
Internals. ReadAllBytes is implemented in an obvious way. It uses the using-statement on a FileStream. Then it loops through the file and puts the bytes into an array. In .NET 4.0, it throws an exception if the file exceeds 2 gigabytes.UsingException
Discussion. You can do amazing things with File.ReadAllBytes. After using File.ReadAllBytes, you can use MemoryStream and BinaryReader to read in a binary file you had previously generated with BinaryWriter. This yields fast file formats.MemoryStreamBinaryReaderBinaryWriter
Notes, memory. File.ReadAllBytes can be used to reduce memory usage. If you have a binary file that contains thousands of sub-resources, you can load the whole file into memory with File.ReadAllBytes as a byte array.

Then: Use BinaryReader to index the contents of the file. Whenever a resource is required, just access the byte range from the byte array.

Note: This can collapse thousands of objects into a single object on the large object heap.

Object
Summary. ReadAllBytes loads a binary file into memory. It has a simple calling pattern and is implemented in a straightforward and efficient way. By combining it with other types, you can develop efficient in-memory database systems.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls