C# File WriteAllBytesAsync() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

In C#, File.WriteAllBytesAsync() creates a file, writes a byte[] into it, and closes the file. If the file already exists, its old content is replaced. It is the async version of File.WriteAllBytes().

It returns a plain Task. Use await so you know the bytes are on disk before the next line runs.

Use it for binary data, or for text you have already turned into bytes with an Encoding.

Syntax

Pass the path and the bytes.

C#
string path = Path.Combine(Path.GetTempPath(), "codetofun-writeallbytesasync.bin");
byte[] data = { 1, 2, 3, 4, 5 };

await File.WriteAllBytesAsync(path, data);

Console.WriteLine(new FileInfo(path).Length);
CallWhat it does
await File.WriteAllBytesAsync(path, bytes)Saves the byte array, creating or replacing the file.
await File.WriteAllBytesAsync(path, memory)Saves a ReadOnlyMemory<byte> instead of an array.
await File.WriteAllBytesAsync(path, bytes, token)Stops with an OperationCanceledException if the token is cancelled.

Use File.AppendAllBytesAsync (.NET 9 and later) when you want to add bytes to the end instead of replacing the file.

Library declarations
C#
public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default);
public static Task WriteAllBytesAsync(string path, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default);

Parameters

ParameterDescription
pathThe file to write. It is created if missing and replaced if it exists.
bytesThe data to save, as a byte[] or a ReadOnlyMemory<byte>.
cancellationTokenOptional. A token that lets you cancel the write before it finishes.

Return Value

Return ValueDescription
TaskA task that completes when the bytes have been written and the file is closed. There is no result value.

C# Examples

Example 1 — Save a Byte Array and Check the File

Write five bytes, then read them back.

C#
using System;
using System.IO;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-writeallbytesasync");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "data.bin");
        byte[] data = { 1, 2, 3, 4, 5 };

        await File.WriteAllBytesAsync(path, data);

        byte[] back = await File.ReadAllBytesAsync(path);
        Console.WriteLine(back.Length);
        Console.WriteLine(string.Join(",", back));

        Directory.Delete(root, true);
    }
}

How It Works

  1. A small array. data holds the numbers one to five. Each fits in a single byte.
  2. One await saves it. WriteAllBytesAsync creates data.bin and writes all five bytes.
  3. Same bytes back. Reading the file returns five bytes, and string.Join prints 1,2,3,4,5.

Example 2 — Write a Shorter Array to Replace the File

Write ten bytes, then three. The file ends up with three.

C#
using System;
using System.IO;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-writeallbytesasync-overwrite");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "block.bin");

        await File.WriteAllBytesAsync(path, new byte[10]);
        Console.WriteLine(new FileInfo(path).Length);

        await File.WriteAllBytesAsync(path, new byte[] { 9, 9, 9 });
        Console.WriteLine(new FileInfo(path).Length);

        Directory.Delete(root, true);
    }
}

How It Works

  1. Ten zero bytes. new byte[10] makes an array of ten zeros, so the file is ten bytes long.
  2. The second write replaces it. The file is emptied first, then three bytes are written.
  3. No leftovers. The length is now 3. The file does not keep the old seven extra bytes.

Example 3 — Turn Text into Bytes and Save It

Encode a word with an Encoding, save the bytes, and decode them again.

C#
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-writeallbytesasync-text");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "word.bin");
        string word = "caf\u00e9";

        byte[] bytes = Encoding.UTF8.GetBytes(word);
        await File.WriteAllBytesAsync(path, bytes);

        byte[] back = await File.ReadAllBytesAsync(path);
        string text = Encoding.UTF8.GetString(back);

        Console.WriteLine(back.Length);
        Console.WriteLine(text.Length);
        Console.WriteLine(text == word);

        Directory.Delete(root, true);
    }
}

How It Works

  1. Encode first. The word has four characters, but the letter with the accent takes two bytes in UTF-8, so GetBytes returns five bytes.
  2. Save and read. The file holds those five bytes, and reading returns the same count.
  3. Decode again. GetString gives back four characters, and the comparison with the original word prints True.

Frequently Asked Questions

It creates a file, writes a byte array into it, and closes the file. If the file exists, the old content is replaced. It returns a Task.
Yes, the whole content is replaced. To add bytes to the end instead, use File.AppendAllBytesAsync on .NET 9 or later.
Turn the text into bytes first, for example Encoding.UTF8.GetBytes(text), then pass the byte array. Or use WriteAllTextAsync, which does that for you.
Yes. There is an overload that takes ReadOnlyMemory<byte>, which is handy when you only want to save part of a buffer.
No. The folder must exist, otherwise you get a DirectoryNotFoundException.

Next: WriteAllLines()

Write an array or sequence of strings as lines, replacing the file.

WriteAllLines() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful