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.
using var fs = new FileStream("data.bin", FileMode.Create, FileAccess.Write); fs.Write(new byte[] { 1, 2, 3 });
Try it
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.
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
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
FileStreamkeeps the file locked and can lose buffered data. Useusing var fs = ...;orawait using. - Choose the mode on purpose.
Createsilently destroys an existing file;CreateNewis the safe "create only if missing" option;OpenOrCreatekeeps existing content and the position stays at 0, so a shorter write leaves old trailing bytes behind (callSetLengthto cut them). - Buffering. Writes sit in a 4 KB buffer until it is full, you call
Flush(), or the stream is disposed. CallFlush(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.Readlets others read the file but blocks writers. On Windows an open file cannot be deleted unlessFileShare.Deleteis granted; Linux and macOS are more relaxed. - Read loops.
Readcan return fewer bytes than requested. Loop until it returns 0 or useReadExactly. - Text.
FileStreamdeals in bytes. For text wrap it in aStreamReaderorStreamWriter; for typed binary values useBinaryReader. - Large files. Hint with
FileOptions.SequentialScanwhen you read from start to end. For fast random access to many offsets,RandomAccess.Read(handle, buffer, offset)withFile.OpenHandleavoids a shared position. - Async. Without
useAsync: true,ReadAsyncandWriteAsyncstill work but run on a thread pool thread. With it, they use overlapped I/O where the operating system supports it. PositionandSeekwork only on seekable file types; pipes and devices opened through aFileStreammay not support them (checkCanSeek).File.OpenRead,File.OpenWrite,File.Createare shortcuts that return aFileStream.File.OpenWritedoes not truncate: an existing longer file keeps its tail.