Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The FileStream class

Reference for System.IO.FileStream in C#: FileMode, FileAccess and FileShare, reading and writing bytes, seeking, buffering, async I/O, locking and exceptions.

FileStream is the Stream that reads and writes a file on disk, byte by byte or in blocks. Use it when the one-call helpers of File are not enough: files too large for memory, random access with Seek, binary formats, control over sharing and locking, or writing a file in pieces.

When you open a FileStream you choose three things. FileMode says what to do if the file exists or not. FileAccess says whether you will read, write, or both. FileShare says what other openers may do while you hold the file. You must dispose it, normally with using, so buffered data is flushed and the file is released.

C#
using var fs = new FileStream("data.bin", FileMode.Create, FileAccess.Write);
fs.Write(new byte[] { 1, 2, 3 });

Try it

C# Write bytes, then read and seek

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# FileMode, locking and async

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public FileStream(string path, FileMode mode);
public FileStream(string path, FileMode mode, FileAccess access);
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync);
public FileStream(string path, FileStreamOptions options);
Parameter Description
mode CreateNew (fail if exists), Create (create or truncate), Open (fail if missing), OpenOrCreate, Truncate (existing file, emptied), Append (write-only, positioned at the end).
access Read, Write or ReadWrite. The default depends on the mode (Append needs Write).
share What others may do meanwhile: None, Read, Write, ReadWrite, Delete. Default is Read.
bufferSize Internal buffer in bytes, default 4096. 0 or 1 disables buffering.
useAsync / FileOptions Asynchronous for async I/O, SequentialScan and RandomAccess as access hints, DeleteOnClose, WriteThrough.
FileStreamOptions A single options object with Mode, Access, Share, Options, BufferSize, PreallocationSize, and UnixCreateMode. Added in .NET 6.

Common members beyond Stream: Name, IsAsync, Flush(bool flushToDisk), Lock(position, length) / Unlock(...), and SafeFileHandle.

Errors: FileNotFoundException, DirectoryNotFoundException, IOException (already exists, in use, disk error), UnauthorizedAccessException (permission, path is a directory), ArgumentException (invalid combinations such as Append with ReadWrite, or Truncate with Read), NotSupportedException (writing to a read-only stream).

Usage notes

  • Always dispose. An undisposed FileStream keeps the file locked and can lose buffered data. Use using var fs = ...; or await using.
  • Choose the mode on purpose. Create silently destroys an existing file; CreateNew is the safe "create only if missing" option; OpenOrCreate keeps existing content and the position stays at 0, so a shorter write leaves old trailing bytes behind (call SetLength to cut them).
  • Buffering. Writes sit in a 4 KB buffer until it is full, you call Flush(), or the stream is disposed. Call Flush(true) to ask the operating system to write through to the disk. Reading while another stream writes the same file needs a flush first.
  • Sharing. The default FileShare.Read lets others read the file but blocks writers. On Windows an open file cannot be deleted unless FileShare.Delete is granted; Linux and macOS are more relaxed.
  • Read loops. Read can return fewer bytes than requested. Loop until it returns 0 or use ReadExactly.
  • Text. FileStream deals in bytes. For text wrap it in a StreamReader or StreamWriter; for typed binary values use BinaryReader.
  • Large files. Hint with FileOptions.SequentialScan when you read from start to end. For fast random access to many offsets, RandomAccess.Read(handle, buffer, offset) with File.OpenHandle avoids a shared position.
  • Async. Without useAsync: true, ReadAsync and WriteAsync still work but run on a thread pool thread. With it, they use overlapped I/O where the operating system supports it.
  • Position and Seek work only on seekable file types; pipes and devices opened through a FileStream may not support them (check CanSeek).
  • File.OpenRead, File.OpenWrite, File.Create are shortcuts that return a FileStream. File.OpenWrite does not truncate: an existing longer file keeps its tail.