ZetCode

C# FileMode

last modified November 6, 2026

In this article we show how to use the FileMode enumeration in C#.

FileMode from the System.IO namespace tells the operating system how to open a file: whether to create it, whether it must already exist, and what to do with its current content. It is passed to the FileStream constructor, File.Open, and FileInfo.Open, usually together with a FileAccess value.

The enumeration has six values:

The examples create a demo directory in the working directory and delete it at the end.

Comparing the modes

The first example opens an existing and a missing file with every mode.

Program.cs
Directory.CreateDirectory("demo");
string existing = Path.Combine("demo", "existing.txt");
string missing = Path.Combine("demo", "missing.txt");

Console.WriteLine($"{"mode",-13} {"existing file",-22} missing file");

foreach (FileMode mode in Enum.GetValues<FileMode>())
{
    File.WriteAllText(existing, "12345");
    File.Delete(missing);

    Console.WriteLine($"{mode,-13} {Open(existing, mode),-22} {Open(missing, mode)}");
}

Directory.Delete("demo", true);

static string Open(string path, FileMode mode)
{
    try
    {
        using var fs = new FileStream(path, mode, FileAccess.Write);
        return $"length {fs.Length}, position {fs.Position}";
    }
    catch (IOException e)
    {
        return e.GetType().Name;
    }
}

Before each mode, the existing file gets five bytes of content and the missing file is deleted. We print the length and position of the opened stream, or the exception.

foreach (FileMode mode in Enum.GetValues<FileMode>())

Enum.GetValues<T> returns all values of the enumeration.

using var fs = new FileStream(path, mode, FileAccess.Write);

We use FileAccess.Write, because it is valid with every mode. Append works only with write access, and CreateNew, Create, and Truncate need at least write access.

The output summarizes the modes. Only Open, OpenOrCreate, and Append keep the content of an existing file, and only Append starts at its end.

$ dotnet run
mode          existing file          missing file
CreateNew     IOException            length 0, position 0
Create        length 0, position 0   length 0, position 0
Open          length 5, position 0   FileNotFoundException
OpenOrCreate  length 5, position 0   length 0, position 0
Truncate      length 0, position 0   FileNotFoundException
Append        length 5, position 5   length 0, position 0

CreateNew for exclusive creation

CreateNew checks and creates the file in one atomic operation. No other process can create the file between the check and the creation, which makes the mode suitable for lock files.

Program.cs
Directory.CreateDirectory("demo");
string lockFile = Path.Combine("demo", "app.lock");

Console.WriteLine($"first instance: {TryLock(lockFile)}");
Console.WriteLine($"second instance: {TryLock(lockFile)}");

File.Delete(lockFile);
Console.WriteLine($"after release: {TryLock(lockFile)}");

Directory.Delete("demo", true);

static bool TryLock(string path)
{
    try
    {
        using var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
        using var writer = new StreamWriter(fs);
        writer.Write(Environment.ProcessId);
        return true;
    }
    catch (IOException)
    {
        return false;
    }
}

A program that should run only once creates a lock file at startup. A second instance fails to create it.

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

If the file exists, the constructor throws an IOException. We write the process ID into the file, so that it can be seen which process holds the lock.

Checking File.Exists and then creating the file with Create would not be safe: two instances could both see that the file is missing and both create it.

$ dotnet run
first instance: True
second instance: False
after release: True

The OpenOrCreate pitfall

OpenOrCreate does not remove the existing content. Writing from the start overwrites only as many bytes as are written.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "message.txt");
File.WriteAllText(path, "hello there");

using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
using (var writer = new StreamWriter(fs))
{
    writer.Write("HEY");
}

Console.WriteLine($"OpenOrCreate: {File.ReadAllText(path)}");

using (FileStream fs = File.OpenWrite(path))
using (var writer = new StreamWriter(fs))
{
    writer.Write("BYE");
}

Console.WriteLine($"File.OpenWrite: {File.ReadAllText(path)}");

using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
using (var writer = new StreamWriter(fs))
{
    writer.Write("HEY");
}

Console.WriteLine($"Create: {File.ReadAllText(path)}");

Directory.Delete("demo", true);

We write three characters to a file that has eleven.

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

The first three characters are replaced and the rest of the old text remains.

using (FileStream fs = File.OpenWrite(path))

File.OpenWrite uses OpenOrCreate as well, so it has the same behavior. This is a common source of corrupted files.

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

To replace the content, use Create, or call SetLength after writing.

$ dotnet run
OpenOrCreate: HEYlo there
File.OpenWrite: BYElo there
Create: HEY

Appending to a file

Append opens the file at its end. Writing can never change the content that was in the file when it was opened.

Program.cs
using System.Text;

Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "events.log");
File.WriteAllText(path, "start\n");

using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
    Console.WriteLine($"position after open: {fs.Position}");
    fs.Write(Encoding.UTF8.GetBytes("stop\n"));

    fs.Seek(-2, SeekOrigin.Current);
    fs.Write(Encoding.UTF8.GetBytes("!\n"));

    try
    {
        fs.Seek(0, SeekOrigin.Begin);
    }
    catch (IOException e)
    {
        Console.WriteLine($"IOException: {e.Message}");
    }
}

Console.Write(File.ReadAllText(path));

Directory.Delete("demo", true);

We append a line to a log, change its last characters, and try to move to the start of the file.

fs.Seek(-2, SeekOrigin.Current);
fs.Write(Encoding.UTF8.GetBytes("!\n"));

Seeking within the newly written data is allowed. We replace the p and the newline of stop.

fs.Seek(0, SeekOrigin.Begin);

Seeking before the original end of the file throws an IOException, so the old data is protected.

$ dotnet run
position after open: 6
IOException: Unable seek backward to overwrite data that previously existed in a file opened in Append mode.
start
sto!

Truncating a file

Truncate opens an existing file and sets its length to zero.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "cache.dat");
File.WriteAllText(path, "old cached data");

using (var fs = new FileStream(path, FileMode.Truncate, FileAccess.Write))
{
    Console.WriteLine($"length after Truncate: {fs.Length}");
    fs.Write("new"u8);
}

Console.WriteLine(File.ReadAllText(path));

File.Delete(path);

try
{
    using var fs = new FileStream(path, FileMode.Truncate, FileAccess.Write);
}
catch (FileNotFoundException)
{
    Console.WriteLine("Truncate on a missing file: FileNotFoundException");
}

Directory.Delete("demo", true);

We empty a file and write new content to it, then try the same with a missing file.

fs.Write("new"u8);

The u8 suffix creates a UTF-8 byte sequence from a string literal.

The difference between Truncate and Create is that Truncate requires the file to exist. It throws FileNotFoundException for a missing file, while Create would create it.

$ dotnet run
length after Truncate: 0
new
Truncate on a missing file: FileNotFoundException

Modes used by the File methods

The helper methods of the File and FileInfo classes choose the mode and access for us.

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

Show("File.Create", () => File.Create(path));
Show("File.OpenWrite", () => File.OpenWrite(path));
Show("File.OpenRead", () => File.OpenRead(path));
Show("FileInfo.Create", () => new FileInfo(path).Create());
Show("File.Open(Append)", () => File.Open(path, FileMode.Append));

Directory.Delete("demo", true);

void Show(string label, Func<FileStream> open)
{
    File.WriteAllText(path, "1234567890");

    using FileStream fs = open();
    Console.WriteLine($"{label,-18} length {fs.Length,2}, position {fs.Position,2}, read {fs.CanRead,-5}, write {fs.CanWrite}");
}

Before each call, the file gets ten bytes. We print the state of the returned stream.

Show("File.Create", () => File.Create(path));
Show("File.OpenWrite", () => File.OpenWrite(path));

File.Create uses FileMode.Create with read and write access, so the file is emptied. File.OpenWrite uses OpenOrCreate and keeps the ten bytes.

Show("File.Open(Append)", () => File.Open(path, FileMode.Append));

File.Open with only a mode uses read and write access, except for Append, where it uses write access.

$ dotnet run
File.Create        length  0, position  0, read True , write True
File.OpenWrite     length 10, position  0, read False, write True
File.OpenRead      length 10, position  0, read True , write False
FileInfo.Create    length  0, position  0, read True , write True
File.Open(Append)  length 10, position 10, read False, write True

Source

FileMode enum

In this article we have worked with the FileMode enumeration 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.