Skip to main content

How to Read a File into a Byte Array with File.ReadAllBytesAsync in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

await File.ReadAllBytesAsync("word.txt") reads the whole of word.txt into a byte[], an array with one number for each byte in the file. It gives you the bytes exactly as they are on disk, whatever the file holds.

Every file on disk is a series of bytes, whether it holds text, a picture or anything else. The .NET API reference on this method: Asynchronously opens a binary file, reads the contents of the file into a byte array, and then closes the file.

What it returns, from the same reference: A task that represents the asynchronous read operation, which wraps the byte array containing the contents of the file. The array comes inside a task, and await takes it out. The C# reference on await: When the asynchronous operation completes, the await operator returns the result of the operation, if any.

Syntax​

Syntax
byte[] <bytes> = await File.ReadAllBytesAsync(<path>);
PartWhat it is
<path>The file to read: a name such as word.txt, a relative path, or a full path
File.ReadAllBytesAsync(<path>)Reads the whole file, and returns a Task<byte[]>: a task that holds the array when the read is done
awaitWaits for the read to finish, and gives you the array from the task
byte[] <bytes>The array. Each byte in it is a whole number from 0 to 255

The Example​

A console app called ReadAllBytes writes the word café to a file named word.txt, so there's a file to read. Then it reads the file back as bytes, and prints how many there are, all of them, and the first and the last two on their own.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ReadAllBytes
cd ReadAllBytes
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ReadAllBytes/ReadAllBytes.csproj:
Determining projects to restore...
Restored /Users/you/source/ReadAllBytes/ReadAllBytes.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n ReadAllBytes creates a folder named ReadAllBytes with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ReadAllBytes.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, a file to read:

Program.cs (a file to read)
// A small file to read: the word café as text.
await File.WriteAllTextAsync("word.txt", "café");

File.WriteAllTextAsync creates word.txt in the current folder and writes café into it. Its await waits until the file is written, so the next line can read it.

Then the read:

Program.cs (read the bytes)
// Read every byte of the file into an array.
byte[] bytes = await File.ReadAllBytesAsync("word.txt");

File.ReadAllBytesAsync("word.txt") reads every byte of the file, and await gives you the array, which bytes keeps.

Then the bytes:

Program.cs (print the bytes)
Console.WriteLine($"word.txt holds {bytes.Length} bytes: {string.Join(" ", bytes)}");
Console.WriteLine($"The first byte is {bytes[0]}, and the last two are {bytes[^2]} and {bytes[^1]}.");

bytes.Length is the number of bytes in the array, and string.Join(" ", bytes) puts them all in one string, with a space between each two. bytes[0] is the first byte. ^ counts from the end, so bytes[^1] is the last byte and bytes[^2] the one before it. The C# reference: The ^ operator indicates the element position from the end of a sequence.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
word.txt holds 5 bytes: 99 97 102 195 169
The first byte is 99, and the last two are 195 and 169.

macOS-style terminal window titled Terminal — ReadAllBytes showing dotnet run printing word.txt holds 5 bytes: 99 97 102 195 169 and The first byte is 99, and the last two are 195 and 169.

café has 4 letters, but word.txt holds 5 bytes. A check that asked Encoding.UTF8.GetBytes for the bytes of each letter on its own printed:

Output
c: 99
a: 97
f: 102
é: 195 169

These are the file's 5 bytes. c, a and f take one byte each, and é takes two, 195 169, the last two bytes in the file. The .NET guide on encoding classes says UTF-8 Represents each Unicode code point as a sequence of one to four bytes. So the number of bytes in a text file isn't always its number of letters.

The Complete File​

macOS-style code window titled Program.cs — ReadAllBytes showing File.WriteAllTextAsync writing café to word.txt, await File.ReadAllBytesAsync reading the file into a byte array, and two Console.WriteLine lines that print the number of bytes, every byte, the first byte and the last two

Program.cs
// A small file to read: the word café as text.
await File.WriteAllTextAsync("word.txt", "café");

// Read every byte of the file into an array.
byte[] bytes = await File.ReadAllBytesAsync("word.txt");

Console.WriteLine($"word.txt holds {bytes.Length} bytes: {string.Join(" ", bytes)}");
Console.WriteLine($"The first byte is {bytes[0]}, and the last two are {bytes[^2]} and {bytes[^1]}.");

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out await, as in byte[] bytes = File.ReadAllBytesAsync("word.txt");The build failed with error CS0029: Cannot implicitly convert type 'System.Threading.Tasks.Task<byte[]>' to 'byte[]'. Without await, the method gives you the task, and not the arrayPut await in front of the call
Printing the array itself, as in Console.WriteLine(bytes);It printed System.Byte[], the name of the array's type, and none of the bytesJoin the bytes into one string first, with string.Join(" ", bytes)
Reading a file that isn't there, as in await File.ReadAllBytesAsync("photo.jpg")The app stopped at the await with Unhandled exception. System.IO.FileNotFoundException: Could not find file '/Users/you/source/ReadAllBytes/photo.jpg'. The reference: If an exception is stored into the returned task, that exception will be thrown when the task is awaited.Check with File.Exists before you read the file

FAQ​

Is there a version without await?​

Yes: File.ReadAllBytes. The reference: Opens a binary file, reads the contents of the file into a byte array, and then closes the file. It returns the array itself, so there's no task to await:

Read the bytes without await
// The synchronous version returns the array itself, with no await.
byte[] bytes = File.ReadAllBytes("word.txt");
Console.WriteLine($"{bytes.Length} bytes: {string.Join(" ", bytes)}");

Run in the same folder, it printed 5 bytes: 99 97 102 195 169, the same bytes. Its reference also lists the exceptions that the async version throws, such as FileNotFoundException for when The file specified in path was not found.

How do I turn the bytes back into text?​

Use Encoding.UTF8.GetString, from the System.Text namespace. The .NET guide on character encoding: The method Encoding.UTF8.GetString performs the opposite transformation, converting a UTF-8 byte array to a UTF-16 string. In other words, it turns the bytes back into a string:

Turn the bytes back into text
using System.Text;

// The bytes read from word.txt, turned back into text.
byte[] bytes = await File.ReadAllBytesAsync("word.txt");
Console.WriteLine(Encoding.UTF8.GetString(bytes));

It printed café: the 5 bytes became the 4 letters again.

Conclusion​

await File.ReadAllBytesAsync(path) reads a whole file into a byte[], with one number from 0 to 255 for each byte in the file. Keep the await, or you get a task instead of the array. Print the bytes with string.Join, not the array itself, and make sure the file is there before you read it. A letter can take more than one byte, so the array's Length counts bytes, not letters.

Additional Resources​