C# File.ReadAllBytes


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: Memory Usage, Read All Bytes



This example shows the basic 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.

Based on:

.NET 4.5

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]);

    Depends on the file found.

First byte: 29
Last byte: 0


Framework: NET

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.



Stream abstract type

You can do some 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.

MemoryStreamBinaryReaderBinaryWriterProgramming tip

File.ReadAllBytes can be used to reduce memory usage for a large data collection. 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.



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.

C#: File