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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).