Home
C#
File.ReadAllBytes, Get Byte Array From File
This page was last reviewed on Dec 24, 2024.
Dot Net Perls
File.ReadAllBytes. This C# method returns a byte array. ReadAllBytes() is simple to call—it receives a file name and returns the file data.
Shows a file
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.
byte Array
File
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.
Shows 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.
using
Exception
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.
MemoryStream
BinaryReader
BinaryWriter
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 Dec 24, 2024 (simplify).
Home
Changes
© 2007-2024 Sam Allen.