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.
Code 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.
And The array can of course be used as any other 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
Internals. 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.
A discussion. 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.
Notes, memory. File.ReadAllBytes can be used to reduce memory usage. If you have a binary file that contains many sub resources, you can load the file into memory with File.ReadAllBytes.
Then Use BinaryReader to index the contents of the file. Whenever are source 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.
A summary. ReadAllBytes loads a binary file into memory. It has a simple calling pattern and is implemented in a straightforward and efficient way.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2023 (edit).