C# FileOptions
last modified November 6, 2026
In this article we show how to use the FileOptions enumeration in
C#.
FileOptions from the System.IO namespace holds
advanced options for opening a file. It is a flags enumeration, so options can
be combined. The options are passed to the operating system when the file is
opened; some of them change the behavior of the file, others are only hints for
the file cache.
Noneuses no additional optionsAsynchronousopens the file for asynchronous I/ODeleteOnClosedeletes the file when it is closedWriteThroughwrites through the system cache directly to the diskRandomAccesshints that the file is accessed at random positionsSequentialScanhints that the file is read from start to endEncryptedencrypts the file with the Windows Encrypting File System
The examples create a demo directory in the working directory and
delete it at the end. The outputs come from Linux.
The enumeration values
The values of FileOptions are the flag values of the Windows
CreateFile function.
foreach (FileOptions option in Enum.GetValues<FileOptions>())
{
Console.WriteLine($"{option,-15} 0x{(uint)option:X8}");
}
We print each value in hexadecimal.
Console.WriteLine($"{option,-15} 0x{(uint)option:X8}");
The underlying type is int, so WriteThrough, the
highest bit, is a negative number. We cast to uint to print it as
an unsigned value.
$ dotnet run None 0x00000000 Encrypted 0x00004000 DeleteOnClose 0x04000000 SequentialScan 0x08000000 RandomAccess 0x10000000 Asynchronous 0x40000000 WriteThrough 0x80000000
Passing options
Options are given in a FileStream constructor or, since .NET 6, in
a FileStreamOptions object.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "data.bin");
var options = new FileStreamOptions
{
Mode = FileMode.Create,
Access = FileAccess.Write,
Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
PreallocationSize = 1024 * 1024,
};
using (var fs = new FileStream(path, options))
{
Console.WriteLine($"IsAsync: {fs.IsAsync}");
await fs.WriteAsync(new byte[1000]);
}
Console.WriteLine($"size: {new FileInfo(path).Length}");
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, FileOptions.SequentialScan))
{
Console.WriteLine($"IsAsync: {fs.IsAsync}");
}
Directory.Delete("demo", true);
We create a file with two options combined and open it again with another option.
Options = FileOptions.Asynchronous | FileOptions.SequentialScan, PreallocationSize = 1024 * 1024,
The Options property takes the combined flags.
PreallocationSize asks the file system to reserve space for the
file in advance, which reduces fragmentation of large files. The file length
is still the number of bytes written.
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, FileOptions.SequentialScan))
In the constructor, the options come after the buffer size. All earlier arguments must be given too.
$ dotnet run IsAsync: True size: 1000 IsAsync: False
Asynchronous I/O
The Asynchronous option opens the file for asynchronous I/O,
which is reported by the IsAsync property.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "numbers.txt");
await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.None, bufferSize: 4096, FileOptions.Asynchronous))
await using (var writer = new StreamWriter(fs))
{
for (int i = 1; i <= 5; i++)
{
await writer.WriteLineAsync($"line {i}");
}
}
await using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.Read, bufferSize: 4096, useAsync: true))
using (var reader = new StreamReader(fs))
{
Console.WriteLine($"IsAsync: {fs.IsAsync}");
string? line;
while ((line = await reader.ReadLineAsync()) is not null)
{
Console.WriteLine(line);
}
}
Directory.Delete("demo", true);
We write lines asynchronously and read them back.
await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.None, bufferSize: 4096, FileOptions.Asynchronous))
With await using, the stream is disposed with
DisposeAsync, which flushes the buffer without blocking.
FileShare.Read, bufferSize: 4096, useAsync: true))
The useAsync parameter of another constructor is a shortcut for
the Asynchronous option.
The async methods such as ReadAsync work on any stream. Without
the option, on Windows they are run on the thread pool; with it, they use
overlapped I/O and do not hold a thread while waiting. The option pays off in
applications with many concurrent file operations. For a single file read in a
loop, synchronous I/O is usually faster.
$ dotnet run IsAsync: True line 1 line 2 line 3 line 4 line 5
Temporary files
DeleteOnClose removes the file when the stream is closed, even if
the program forgets to delete it.
string path = Path.Combine(Path.GetTempPath(), $"work-{Guid.NewGuid():N}.tmp");
using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite,
FileShare.None, bufferSize: 4096, FileOptions.DeleteOnClose))
{
fs.Write(new byte[64 * 1024]);
Console.WriteLine($"while open: exists {File.Exists(path)}, {fs.Length} bytes");
fs.Position = 0;
Console.WriteLine($"read back {fs.Read(new byte[1024])} bytes");
}
Console.WriteLine($"after close: exists {File.Exists(path)}");
We create a working file in the temporary directory, write to it, read from it, and close it.
string path = Path.Combine(Path.GetTempPath(), $"work-{Guid.NewGuid():N}.tmp");
A GUID gives the file a unique name. We open it with
CreateNew, so an existing file is never reused.
Console.WriteLine($"after close: exists {File.Exists(path)}");
After the stream is disposed, the file is gone. If the process is killed, the file may remain on Linux, while on Windows the system deletes it when the last handle is closed.
$ dotnet run while open: exists True, 65536 bytes read back 1024 bytes after close: exists False
Writing through the cache
Normally the operating system collects writes in memory and writes them to the
disk later. WriteThrough makes each write go to the disk before
the call returns.
using System.Diagnostics;
Directory.CreateDirectory("demo");
byte[] record = new byte[100];
Console.WriteLine($"None: {Measure(FileOptions.None)} ms");
Console.WriteLine($"WriteThrough: {Measure(FileOptions.WriteThrough)} ms");
Directory.Delete("demo", true);
long Measure(FileOptions options)
{
string path = Path.Combine("demo", $"{options}.log");
var sw = Stopwatch.StartNew();
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.None, bufferSize: 0, options))
{
for (int i = 0; i < 200; i++)
{
fs.Write(record);
}
}
return sw.ElapsedMilliseconds;
}
We write 200 records of 100 bytes with and without the option and measure the time.
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.None, bufferSize: 0, options))
A buffer size of 0 turns off the buffer of FileStream, so each
Write call is passed to the operating system.
On this machine with an NVMe SSD, the write-through version is several hundred times slower. Use the
option only for data that must survive a power failure, such as a transaction
log. Calling Flush(flushToDisk: true) at chosen points is often a
better compromise.
$ dotnet run None: 1 ms WriteThrough: 402 ms
Random access
RandomAccess and SequentialScan tell the system how
the file will be read, so it can adjust how much data it reads ahead. They do
not change the result of any operation.
using Microsoft.Win32.SafeHandles;
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "records.bin");
const int recordSize = 16;
byte[] data = new byte[recordSize * 1000];
for (int i = 0; i < 1000; i++)
{
BitConverter.TryWriteBytes(data.AsSpan(i * recordSize), i * i);
}
File.WriteAllBytes(path, data);
using (SafeFileHandle handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read,
FileShare.Read, FileOptions.RandomAccess))
{
byte[] buffer = new byte[recordSize];
foreach (int index in new[] { 999, 7, 512 })
{
RandomAccess.Read(handle, buffer, fileOffset: (long)index * recordSize);
Console.WriteLine($"record {index}: {BitConverter.ToInt32(buffer)}");
}
Console.WriteLine($"file length: {RandomAccess.GetLength(handle)}");
}
Directory.Delete("demo", true);
We store 1000 records of 16 bytes and read three of them by index.
using (SafeFileHandle handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read,
FileShare.Read, FileOptions.RandomAccess))
File.OpenHandle, added in .NET 6, opens a file without a stream
and returns a handle.
RandomAccess.Read(handle, buffer, fileOffset: (long)index * recordSize);
The static RandomAccess class reads and writes at a given offset.
It has no current position, so it can be used from several threads at once.
The cast to long avoids an overflow for files larger than 2 GB.
$ dotnet run record 999: 998001 record 7: 49 record 512: 262144 file length: 16000
Platform differences
Not every option has an effect on every system.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "secret.dat");
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.None, bufferSize: 4096, FileOptions.Encrypted))
{
fs.Write("secret"u8);
}
Console.WriteLine($"attributes: {File.GetAttributes(path)}");
try
{
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.Read, bufferSize: 4096, (FileOptions)1);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}
Directory.Delete("demo", true);
We create a file with the Encrypted option and open a file with
an invalid option value.
FileShare.None, bufferSize: 4096, FileOptions.Encrypted))
On Windows, the file is encrypted with EFS and gets the
Encrypted attribute. On Linux the option is silently ignored, as
the attributes in the output show. Do not rely on it to protect data on other
systems.
FileShare.Read, bufferSize: 4096, (FileOptions)1);
Values that are not defined in the enumeration are rejected with an
ArgumentOutOfRangeException.
$ dotnet run attributes: Normal ArgumentOutOfRangeException: Enum value was out of legal range. (Parameter 'options')
Source
In this article we have worked with the FileOptions enumeration in
C#.
Author
List all C# tutorials.