ZetCode

C# FileStream

last modified November 6, 2026

In this article we show how to read and write files with the FileStream class in C#.

FileStream from the System.IO namespace provides a Stream for a file. It reads and writes bytes, supports moving to any position in the file, and buffers the data to reduce the number of calls to the operating system. Text readers and writers, binary readers and writers, compression streams, and many libraries work on top of a FileStream.

A stream holds an open file handle, so it must be disposed, which is done with a using statement. The examples create a demo directory in the working directory and delete it at the end.

Writing and reading bytes

The first example writes text as bytes to a file and reads it back.

Program.cs
using System.Text;

Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "hello.txt");

using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
    byte[] data = Encoding.UTF8.GetBytes("Hello from FileStream\n");
    fs.Write(data);

    Console.WriteLine($"Name: {Path.GetFileName(fs.Name)}");
    Console.WriteLine($"Length: {fs.Length}, Position: {fs.Position}");
    Console.WriteLine($"CanRead: {fs.CanRead}, CanWrite: {fs.CanWrite}, CanSeek: {fs.CanSeek}");
}

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    byte[] buffer = new byte[fs.Length];
    fs.ReadExactly(buffer);

    Console.Write(Encoding.UTF8.GetString(buffer));
}

Directory.Delete("demo", true);

We open the file for writing, write the UTF-8 bytes of a string, and print the properties of the stream.

using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))

The constructor takes the path, a FileMode that says how to open the file, and a FileAccess that says what we want to do with it.

fs.Write(data);

Write accepts a byte array or a span. After the write, the position is at the end of the written data.

fs.ReadExactly(buffer);

ReadExactly, added in .NET 7, fills the buffer completely or throws an EndOfStreamException. The older Read(buffer, 0, buffer.Length) may return fewer bytes than requested, and code that ignores its return value is a common bug.

$ dotnet run
Name: hello.txt
Length: 22, Position: 22
CanRead: False, CanWrite: True, CanSeek: True
Hello from FileStream

Reading in chunks

Large files are read in pieces with a fixed buffer, so memory use does not depend on the file size.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "data.bin");
File.WriteAllBytes(path, new byte[10_000]);

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    byte[] buffer = new byte[4096];
    int bytesRead;
    long total = 0;

    while ((bytesRead = fs.Read(buffer)) > 0)
    {
        total += bytesRead;
        Console.WriteLine($"read {bytesRead} bytes, position {fs.Position}");
    }

    Console.WriteLine($"total: {total} bytes");
}

Directory.Delete("demo", true);

We read a file of 10,000 bytes with a 4 KB buffer.

while ((bytesRead = fs.Read(buffer)) > 0)

Read returns the number of bytes it put into the buffer, and 0 at the end of the file. Only the first bytesRead bytes of the buffer are valid; the last chunk is shorter than the buffer.

$ dotnet run
read 4096 bytes, position 4096
read 4096 bytes, position 8192
read 1808 bytes, position 10000
total: 10000 bytes

Binary values

Numbers are stored in binary files as fixed numbers of bytes. The BinaryPrimitives class converts values to and from bytes with an explicit byte order.

Program.cs
using System.Buffers.Binary;

Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "point.bin");

using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
    Span<byte> buffer = stackalloc byte[17];

    BinaryPrimitives.WriteInt32LittleEndian(buffer, 42);
    BinaryPrimitives.WriteDoubleLittleEndian(buffer[4..], 3.14159);
    BinaryPrimitives.WriteInt32LittleEndian(buffer[12..], -7);
    buffer[16] = 1;

    fs.Write(buffer);
}

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    Span<byte> buffer = stackalloc byte[17];
    fs.ReadExactly(buffer);

    int id = BinaryPrimitives.ReadInt32LittleEndian(buffer);
    double value = BinaryPrimitives.ReadDoubleLittleEndian(buffer[4..]);
    int offset = BinaryPrimitives.ReadInt32LittleEndian(buffer[12..]);
    bool active = buffer[16] != 0;

    Console.WriteLine($"{id} {value} {offset} {active}");
    Console.WriteLine(Convert.ToHexString(buffer));
}

Directory.Delete("demo", true);

We write a record of an integer, a double, another integer, and a boolean, 17 bytes in total.

Span<byte> buffer = stackalloc byte[17];

The record is built in a buffer on the stack, so no array is allocated.

BinaryPrimitives.WriteDoubleLittleEndian(buffer[4..], 3.14159);

Each value is written at its offset. The range buffer[4..] is the part of the span starting at byte 4. Little-endian order puts the least significant byte first.

Console.WriteLine(Convert.ToHexString(buffer));

The hexadecimal dump shows the layout: 2A000000 is 42, then come the eight bytes of the double, F9FFFFFF is -7 in two's complement, and 01 is true. For records with many fields, BinaryWriter and BinaryReader are more convenient.

$ dotnet run
42 3.14159 -7 True
2A0000006E861BF0F9210940F9FFFFFF01

Seeking

A file stream can move to any position with the Seek method or the Position property.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "bytes.bin");
File.WriteAllBytes(path, new byte[20]);

using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
    fs.Seek(2, SeekOrigin.Begin);
    fs.WriteByte(0xAA);

    fs.Seek(5, SeekOrigin.Current);
    fs.WriteByte(0xBB);

    fs.Seek(-1, SeekOrigin.End);
    fs.WriteByte(0xCC);

    fs.Position = 30;
    fs.WriteByte(0xDD);
    Console.WriteLine($"length after writing past the end: {fs.Length}");

    fs.SetLength(24);
    Console.WriteLine($"length after SetLength: {fs.Length}");
}

Console.WriteLine(Convert.ToHexString(File.ReadAllBytes(path)));

Directory.Delete("demo", true);

We create a file of 20 zero bytes and change bytes at several positions.

fs.Seek(2, SeekOrigin.Begin);
fs.WriteByte(0xAA);

fs.Seek(5, SeekOrigin.Current);
fs.WriteByte(0xBB);

fs.Seek(-1, SeekOrigin.End);
fs.WriteByte(0xCC);

SeekOrigin sets what the offset is relative to: the start, the current position, or the end. After writing at position 2, the position is 3, so the second byte goes to position 8. The third overwrites the last byte.

fs.Position = 30;
fs.WriteByte(0xDD);

Writing past the end extends the file; the gap is filled with zeros.

fs.SetLength(24);

SetLength shortens or extends the file. Here it cuts off the byte written at position 30.

$ dotnet run
length after writing past the end: 31
length after SetLength: 24
0000AA0000000000BB00000000000000000000CC00000000

Copying streams and hashing

Many APIs accept a Stream, so a file can be passed to them without loading it into memory.

Program.cs
using System.Security.Cryptography;

Directory.CreateDirectory("demo");
string source = Path.Combine("demo", "source.bin");
string target = Path.Combine("demo", "target.bin");

byte[] data = new byte[1_000_000];
new Random(1).NextBytes(data);
File.WriteAllBytes(source, data);

using (var input = new FileStream(source, FileMode.Open, FileAccess.Read))
using (var output = new FileStream(target, FileMode.Create, FileAccess.Write))
{
    input.CopyTo(output);
}

Console.WriteLine($"{Hash(source)}  source.bin");
Console.WriteLine($"{Hash(target)}  target.bin");

Directory.Delete("demo", true);

static string Hash(string path)
{
    using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
    return Convert.ToHexStringLower(SHA256.HashData(fs))[..16];
}

We copy a file of one million bytes and compare the hashes of both files.

input.CopyTo(output);

CopyTo reads the input and writes it to the output with an internal buffer.

return Convert.ToHexStringLower(SHA256.HashData(fs))[..16];

SHA256.HashData reads the stream to the end and computes its hash. We print the first 16 hexadecimal digits. Equal hashes show that the copy is identical to the source.

$ dotnet run
ebcafe9229d72710  source.bin
ebcafe9229d72710  target.bin

Buffering

FileStream buffers data in memory, 4096 bytes by default, and passes it to the operating system in larger blocks.

Program.cs
using System.Diagnostics;

Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "big.bin");
const int size = 1_000_000;

foreach (int bufferSize in new[] { 0, 4096, 81920 })
{
    var sw = Stopwatch.StartNew();

    using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize))
    {
        for (int i = 0; i < size; i++)
        {
            fs.WriteByte((byte)i);
        }
    }

    Console.WriteLine($"buffer {bufferSize,6}: {sw.ElapsedMilliseconds,5} ms");
}

Directory.Delete("demo", true);

We write one million bytes one at a time with different buffer sizes.

using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize))

A buffer size of 0 or 1 turns buffering off, so each WriteByte becomes a system call. On this machine, that is about a hundred times slower. A larger buffer than the default gives little additional gain. Writing large blocks with Write instead of single bytes makes the buffer size matter much less.

$ dotnet run
buffer      0:   425 ms
buffer   4096:     4 ms
buffer  81920:     4 ms

Asynchronous I/O

The asynchronous methods do not block the calling thread, which keeps user interfaces responsive and lets servers handle other requests while waiting for the disk.

Program.cs
using System.Text;

Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "words.txt");

var writeOptions = new FileStreamOptions
{
    Mode = FileMode.Create,
    Access = FileAccess.Write,
    Options = FileOptions.Asynchronous,
};

await using (var fs = new FileStream(path, writeOptions))
{
    foreach (string word in new[] { "sky", "cloud", "rain" })
    {
        await fs.WriteAsync(Encoding.UTF8.GetBytes(word + "\n"));
    }
}

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

await using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
    bufferSize: 4096, useAsync: true))
{
    byte[] buffer = new byte[fs.Length];
    await fs.ReadExactlyAsync(buffer, cts.Token);

    Console.Write(Encoding.UTF8.GetString(buffer));
}

Directory.Delete("demo", true);

We write three words asynchronously and read the file back.

Options = FileOptions.Asynchronous,

The Asynchronous option opens the file for asynchronous I/O. The useAsync constructor parameter does the same.

await using (var fs = new FileStream(path, writeOptions))

With await using, the stream is disposed with DisposeAsync, which writes the remaining buffer asynchronously.

await fs.ReadExactlyAsync(buffer, cts.Token);

The async methods accept a CancellationToken. Here the token cancels the read if it takes more than five seconds.

$ dotnet run
sky
cloud
rain

Flushing

Written data stays in the buffer of the stream until the buffer is full, the stream is flushed, or it is disposed.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "journal.bin");

using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
    fs.Write([1, 2, 3]);
    Console.WriteLine($"before Flush: {new FileInfo(path).Length} bytes in the file");

    fs.Flush();
    Console.WriteLine($"after Flush: {new FileInfo(path).Length} bytes in the file");

    fs.Write([4, 5, 6]);
    fs.Flush(flushToDisk: true);
    Console.WriteLine($"after Flush(true): {new FileInfo(path).Length} bytes in the file");
}

Directory.Delete("demo", true);

We write bytes and check the file size reported by the file system.

fs.Flush();

Flush passes the buffered data to the operating system, which makes it visible to other programs. The operating system may still keep it in its own cache.

fs.Flush(flushToDisk: true);

Flush(true) also asks the operating system to write its cache to the disk, so the data survives a power failure. It is slow and should be used only at points where durability matters.

$ dotnet run
before Flush: 0 bytes in the file
after Flush: 3 bytes in the file
after Flush(true): 6 bytes in the file

Source

FileStream class

In this article we have read and written files with the FileStream class in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.