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. A stream is a sequence of bytes with a current position; it supports reading, writing, and, for files, seeking. FileStream works with bytes. For text, we wrap it in a StreamReader or StreamWriter, which handle the encoding.

This article shows common tasks. The FileStream class article covers the constructor options, buffering, sharing, and other details.

Writing bytes

The first example writes text to a file as UTF-8 bytes.

Program.cs
using System.Text;

using (var fs = File.Create("words.txt"))
{
    byte[] bytes = Encoding.UTF8.GetBytes("falcon\nhawk\nforest\ncloud\nsky\n");
    fs.Write(bytes);

    Console.WriteLine($"Wrote {bytes.Length} bytes, position {fs.Position}");
}

Console.Write(File.ReadAllText("words.txt"));
File.Delete("words.txt");

File.Create creates a new file, or truncates an existing one, and returns a FileStream open for writing.

byte[] bytes = Encoding.UTF8.GetBytes("falcon\nhawk\nforest\ncloud\nsky\n");
fs.Write(bytes);

A FileStream accepts only bytes, so we encode the text first. Write advances the position by the number of bytes written.

$ dotnet run
Wrote 29 bytes, position 29
falcon
hawk
forest
cloud
sky

File.OpenWrite does not truncate

File.OpenWrite opens a file for writing, but it does not remove the existing content. It uses FileMode.OpenOrCreate, so writing fewer bytes than the file has leaves the old tail in place.

Program.cs
using System.Text;

File.WriteAllText("status.txt", "status: running\n");

using (var fs = File.OpenWrite("status.txt"))
{
    fs.Write(Encoding.UTF8.GetBytes("ok\n"));
}

Console.Write($"OpenWrite: {File.ReadAllText("status.txt").Replace("\n", "\\n")}\n");

using (var fs = File.Create("status.txt"))
{
    fs.Write(Encoding.UTF8.GetBytes("ok\n"));
}

Console.Write($"Create:    {File.ReadAllText("status.txt").Replace("\n", "\\n")}\n");

File.Delete("status.txt");

The file contains status: running. We overwrite it with ok in two ways.

With OpenWrite, the first three bytes are replaced and the rest of the old text remains. File.Create, which uses FileMode.Create, gives the expected result.

$ dotnet run
OpenWrite: ok\ntus: running\n
Create:    ok\n

Writing text with StreamWriter

A StreamWriter over a FileStream encodes the text for us.

Program.cs
using (var fs = new FileStream("words.txt", FileMode.Create, FileAccess.Write))
using (var writer = new StreamWriter(fs))
{
    writer.WriteLine("coin");
    writer.WriteLine("falcon");
    writer.WriteLine($"{3} birds");
}

using (var fs = new FileStream("words.txt", FileMode.Append))
using (var writer = new StreamWriter(fs))
{
    writer.WriteLine("appended");
}

Console.Write(File.ReadAllText("words.txt"));
File.Delete("words.txt");

The FileStream constructor takes the mode and the access explicitly.

using (var fs = new FileStream("words.txt", FileMode.Append))

FileMode.Append opens the file, or creates it, and moves to its end. It allows only writing.

Disposing the writer flushes its buffer and closes the stream. The second using for the stream is still good practice in case the writer constructor throws.

$ dotnet run
coin
falcon
3 birds
appended

Reading bytes in chunks

Reading text as bytes in chunks has a trap: a chunk boundary can fall in the middle of a multi-byte UTF-8 character.

Program.cs
using System.Text;

File.WriteAllText("words.txt", "\u017Eltu\u010Dk\u00FD k\u00F4\u0148");

Console.WriteLine($"Chunks:  {Escape(ReadChunks(s => Encoding.UTF8.GetString(s)))}");

Decoder decoder = Encoding.UTF8.GetDecoder();
Console.WriteLine($"Decoder: {Escape(ReadChunks(s =>
{
    var chars = new char[s.Length];
    int n = decoder.GetChars(s, chars, flush: false);
    return new string(chars, 0, n);
}))}");

File.Delete("words.txt");

static string ReadChunks(Func<ReadOnlySpan<byte>, string> decode)
{
    using var fs = File.OpenRead("words.txt");
    var buffer = new byte[3];
    var sb = new StringBuilder();
    int n;

    while ((n = fs.Read(buffer)) > 0)
    {
        sb.Append(decode(buffer.AsSpan(0, n)));
    }

    return sb.ToString();
}

static string Escape(string s) =>
    string.Concat(s.Select(c => c < 128 ? c.ToString() : $"\\u{(int) c:X4}"));

We read a Slovak phrase with a three-byte buffer and decode each chunk in two ways. A small buffer makes the problem visible; with a real buffer it happens less often, but it does happen.

Console.WriteLine($"Chunks:  {Escape(ReadChunks(s => Encoding.UTF8.GetString(s)))}");

Decoding each chunk on its own turns the split characters into U+FFFD replacement characters. The text is corrupted.

Decoder decoder = Encoding.UTF8.GetDecoder();

A Decoder keeps incomplete byte sequences between calls and completes them with the next chunk. StreamReader uses a decoder internally, which is why it is the better way to read text.

$ dotnet run
Chunks:  \u017Eltu\uFFFD\uFFFDk\uFFFD\uFFFD k\u00F4\uFFFD\uFFFD
Decoder: \u017Eltu\u010Dk\u00FD k\u00F4\u0148

Reading text with StreamReader

A StreamReader over a FileStream reads the file line by line.

Program.cs
File.WriteAllLines("words.txt", ["coin", "falcon", "hawk", "forest"]);

using var fs = new FileStream("words.txt", FileMode.Open, FileAccess.Read);
using var reader = new StreamReader(fs);

string? line;
int n = 0;

while ((line = reader.ReadLine()) is not null)
{
    Console.WriteLine($"{++n}. {line}");
}

reader.Dispose();
File.Delete("words.txt");

We open the stream for reading and pass it to the reader.

while ((line = reader.ReadLine()) is not null)

ReadLine returns null at the end of the file.

$ dotnet run
1. coin
2. falcon
3. hawk
4. forest

Seeking

A file stream can move to any position. With fixed-size records, we can read a record without reading the ones before it.

Program.cs
using System.Text;

const int RecordSize = 12;
string[] names = ["Anna", "Peter", "Lucia", "Thomas", "Eva"];

using (var fs = File.Create("people.dat"))
{
    foreach (var name in names)
    {
        fs.Write(Encoding.ASCII.GetBytes(name.PadRight(RecordSize)));
    }
}

using (var fs = File.OpenRead("people.dat"))
{
    Console.WriteLine($"File size: {fs.Length} bytes, {fs.Length / RecordSize} records");

    var record = new byte[RecordSize];

    foreach (int index in new[] { 3, 0, 4 })
    {
        fs.Seek(index * RecordSize, SeekOrigin.Begin);
        fs.ReadExactly(record);

        Console.WriteLine($"Record {index}: {Encoding.ASCII.GetString(record).TrimEnd()}");
    }

    fs.Seek(-RecordSize, SeekOrigin.End);
    fs.ReadExactly(record);
    Console.WriteLine($"Last record: {Encoding.ASCII.GetString(record).TrimEnd()}");
}

File.Delete("people.dat");

Each name is padded to 12 bytes, so record n starts at byte n * 12.

fs.Seek(index * RecordSize, SeekOrigin.Begin);
fs.ReadExactly(record);

Seek sets the position relative to the beginning. ReadExactly reads exactly 12 bytes or throws an EndOfStreamException.

fs.Seek(-RecordSize, SeekOrigin.End);

A negative offset from SeekOrigin.End moves back from the end of the file.

$ dotnet run
File size: 60 bytes, 5 records
Record 3: Thomas
Record 0: Anna
Record 4: Eva
Last record: Eva

CopyTo

CopyTo reads a stream from its current position to the end and writes the data to another stream.

Program.cs
File.WriteAllText("words.txt", "sky\nblue\nforest\n");

using (var source = new FileStream("words.txt", FileMode.Open, FileAccess.Read))
using (var target = new FileStream("words_copy.txt", FileMode.Create, FileAccess.Write))
{
    source.CopyTo(target);
    Console.WriteLine($"Copied {target.Length} bytes");
}

Console.Write(File.ReadAllText("words_copy.txt"));

File.Delete("words.txt");
File.Delete("words_copy.txt");

We copy a text file into a new file. For plain file copies, File.Copy is simpler; CopyTo is useful when one side is not a file, for example a network or a compression stream.

$ dotnet run
Copied 16 bytes
sky
blue
forest

Saving a downloaded image

This example downloads a PNG image, saves it, and prints its first bytes in hexadecimal.

Program.cs
using var client = new HttpClient();
byte[] image = await client.GetByteArrayAsync("https://httpbin.org/image/png");

using (var fs = new FileStream("image.png", FileMode.Create))
{
    fs.Write(image);
}

Console.WriteLine($"Saved {new FileInfo("image.png").Length} bytes");

using (var fs = new FileStream("image.png", FileMode.Open))
{
    int c;
    int i = 0;

    while ((c = fs.ReadByte()) != -1 && i < 32)
    {
        Console.Write($"{c:X2} ");
        i++;

        if (i % 16 == 0)
        {
            Console.WriteLine();
        }
    }
}

File.Delete("image.png");

GetByteArrayAsync downloads the whole image into memory, which is fine for small files.

while ((c = fs.ReadByte()) != -1 && i < 32)

ReadByte returns the next byte, or -1 at the end. We print the first 32 bytes, 16 per line.

Every PNG file starts with the signature 89 50 4E 47 0D 0A 1A 0A, whose bytes 2 to 4 are PNG in ASCII. It is followed by the IHDR chunk with the image width and height, here 100 by 100 pixels (00 00 00 64).

$ dotnet run
Saved 8090 bytes
89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 
00 00 00 64 00 00 00 64 08 02 00 00 00 FF 80 02 

Streaming a download

For large files, we copy the response to the file as it arrives instead of loading it into memory.

Program.cs
using var client = new HttpClient();
var url = "https://www.gutenberg.org/cache/epub/1342/pg1342.txt";

using var resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
resp.EnsureSuccessStatusCode();

long? total = resp.Content.Headers.ContentLength;
Console.WriteLine($"Content-Length: {total:N0} bytes");

await using Stream body = await resp.Content.ReadAsStreamAsync();
await using var fs = File.Create("book.txt");

var buffer = new byte[81920];
long received = 0;
int n;
int nextReport = 25;

while ((n = await body.ReadAsync(buffer)) > 0)
{
    await fs.WriteAsync(buffer.AsMemory(0, n));
    received += n;

    if (total is > 0 && received * 100 / total >= nextReport)
    {
        Console.WriteLine($"{received * 100 / total,3}% ({received:N0} bytes)");
        nextReport += 25;
    }
}

await fs.DisposeAsync();
File.Delete("book.txt");

We download a book from Project Gutenberg and report the progress.

using var resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

With ResponseHeadersRead, GetAsync completes as soon as the headers arrive; the body is not buffered.

while ((n = await body.ReadAsync(buffer)) > 0)
{
    await fs.WriteAsync(buffer.AsMemory(0, n));

We read the response stream in blocks and write each block to the file. Only one 80 KB buffer is in memory at a time. Without progress reporting, await body.CopyToAsync(fs) does the same.

The progress uses the Content-Length header. The reported percentages vary between runs, as they depend on how much data each read returns.

$ dotnet run
Content-Length: 772,386 bytes
 26% (206,320 bytes)
 52% (402,160 bytes)
 77% (598,000 bytes)
100% (772,386 bytes)

Source

FileStream class

In this article we have read and written files with FileStream, both as bytes and as text, sought to records, copied streams, and saved downloads.

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.