Skip to main content

How to Write Bytes to a File with File.WriteAllBytesAsync in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

await File.WriteAllBytesAsync("greeting.txt", bytes) saves the bytes of a byte[] in a file named greeting.txt. It creates the file when it isn't there, and replaces everything in it when it is.

A byte[] is an array of bytes, and each byte is a whole number from 0 to 255. File.WriteAllBytesAsync puts those numbers in a file exactly as they are. The .NET API reference: Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten.

What it returns, from the same reference: A task that represents the asynchronous write operation. There's no value in this task, so await gives nothing back: it waits until the bytes are written.

Syntax​

Syntax
await File.WriteAllBytesAsync(<path>, <bytes>);
PartWhat it is
<path>The file to write: a name such as greeting.txt, a relative path, or a full path. Its folder has to exist
<bytes>A byte[] with the bytes to save
File.WriteAllBytesAsync(<path>, <bytes>)Writes the bytes, and returns a Task that's done when the file is written and closed
awaitWaits until that task is done

The Example​

A console app called WriteAllBytes writes 5 bytes to a file named greeting.txt, the codes of the letters in Hello, and reads the file back as text to show what's in it. Then it writes 2 bytes to the same file, to show that the second write replaces the first one.

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 WriteAllBytes
cd WriteAllBytes
Output
The template "Console App" was created successfully.

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

dotnet new console -n WriteAllBytes creates a folder named WriteAllBytes 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 WriteAllBytes.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, 5 bytes:

Program.cs (write 5 bytes)
// The letters H, e, l, l and o as bytes: their character codes.
byte[] hello = [72, 101, 108, 108, 111];
await File.WriteAllBytesAsync("greeting.txt", hello);
Console.WriteLine($"Wrote {hello.Length} bytes: {await File.ReadAllTextAsync("greeting.txt")}");

[72, 101, 108, 108, 111] makes a byte[] with 5 numbers in it. The C# reference on this syntax, a collection expression: A collection expression contains a sequence of elements between [ and ] brackets. The numbers are the codes of H, e, l, l and o. File.WriteAllBytesAsync writes them to greeting.txt, and File.ReadAllTextAsync reads the file back as text, so you can see what it holds.

Then 2 bytes, to the same file:

Program.cs (write 2 bytes to the same file)
// Writing again replaces the whole file, even with fewer bytes.
byte[] hi = [72, 105];
await File.WriteAllBytesAsync("greeting.txt", hi);
Console.WriteLine($"Wrote {hi.Length} bytes: {await File.ReadAllTextAsync("greeting.txt")}");

[72, 105] are the codes of H and i. This time greeting.txt is already there.

Step 3: Run It​

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

Terminal
dotnet run
Output
Wrote 5 bytes: Hello
Wrote 2 bytes: Hi

macOS-style terminal window titled Terminal — WriteAllBytes showing dotnet run printing Wrote 5 bytes: Hello and Wrote 2 bytes: Hi

The first write created greeting.txt with 5 bytes, which read back as Hello. The second write had only 2 bytes, and after it the file held just Hi: nothing from the first write was left. That's the truncated and overwritten in the reference: none of the old content is kept, even when the new bytes are fewer.

The Complete File​

macOS-style code window titled Program.cs — WriteAllBytes showing a byte array with the codes of H, e, l, l and o written to greeting.txt with await File.WriteAllBytesAsync and read back with File.ReadAllTextAsync, then a second byte array with the codes of H and i written to the same file and read back

Program.cs
// The letters H, e, l, l and o as bytes: their character codes.
byte[] hello = [72, 101, 108, 108, 111];
await File.WriteAllBytesAsync("greeting.txt", hello);
Console.WriteLine($"Wrote {hello.Length} bytes: {await File.ReadAllTextAsync("greeting.txt")}");

// Writing again replaces the whole file, even with fewer bytes.
byte[] hi = [72, 105];
await File.WriteAllBytesAsync("greeting.txt", hi);
Console.WriteLine($"Wrote {hi.Length} bytes: {await File.ReadAllTextAsync("greeting.txt")}");

Common Mistakes​

MistakeWhat happensDo this instead
Writing into a folder that isn't there, as in File.WriteAllBytesAsync("out/greeting.txt", hi) with no out folderThe app stopped with Unhandled exception. System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/you/source/WriteAllBytes/out/greeting.txt'. The method creates the file, not the folder it goes inCreate the folder first with Directory.CreateDirectory("out"). With that line first, a check printed out/greeting.txt exists: True
Passing text, as in File.WriteAllBytesAsync("greeting.txt", "Hello")The build failed with error CS1503: Argument 2: cannot convert from 'string' to 'byte[]'For text, use File.WriteAllTextAsync, which takes a string
A number over 255 in the array, as in byte[] bytes = [72, 300];The build failed with error CS0029: Cannot implicitly convert type 'int' to 'byte'. A byte holds only 0 to 255, so 300 doesn't fit in oneKeep every number in the array from 0 to 255

FAQ​

How do I write only part of an array?​

Pass AsMemory(start, length) instead of the whole array. The .NET API reference: Creates a new memory region over the portion of the target array beginning at a specified position with a specified length. In .NET 9 and later, File.WriteAllBytesAsync also accepts that region:

Write 4 of the 5 bytes
byte[] hello = [72, 101, 108, 108, 111];

// AsMemory(1, 4): 4 bytes, starting at position 1.
await File.WriteAllBytesAsync("part.txt", hello.AsMemory(1, 4));
Console.WriteLine($"part.txt: {await File.ReadAllTextAsync("part.txt")}");

It printed part.txt: ello. Position 0 is the H, so starting at position 1 left it out, and the 4 bytes after it were written.

Is there a version without await?​

Yes: File.WriteAllBytes. The reference: Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten. It returns nothing, so there's no task to await:

Write the bytes without await
// The synchronous version writes the bytes with no await.
byte[] hi = [72, 105];
File.WriteAllBytes("greeting.txt", hi);
Console.WriteLine($"greeting.txt: {File.ReadAllText("greeting.txt")}");

It printed greeting.txt: Hi.

Conclusion​

await File.WriteAllBytesAsync(path, bytes) saves a byte[] in a file. It creates the file, or empties it and writes it again when it's already there. Make sure the folder in the path exists, pass bytes and not a string, and keep every number from 0 to 255. To save only part of an array, pass AsMemory(start, length).

Additional Resources​