CodeGym /Courses /C# SELF /File Opening Modes

File Opening Modes

C# SELF
Level 35, Lesson 4
Available

1. Introduction

When you're working with files using FileStream or other stream classes, it's super important to know ahead of time what exactly will happen to the file when you try to open it. It's pretty common to run into a situation where the file already exists, and you either want to add new data without losing the old stuff, or you want to completely overwrite the file. On the flip side, sometimes the file isn't created yet, and you want to read it without accidentally creating an empty file.

For example, if you're writing a notepad for daily notes, your job is to add new entries to the end of an existing file, keeping everything that was written before. That means you need to open the file in append mode. In another case—let's say you have a log file that should be created fresh every time the app starts, so old data doesn't get in the way. Here, you want to open the file so that it gets cleared or created if it doesn't exist. And if your task is just to read an existing file, you probably want to make sure you don't create a new file if it doesn't exist, otherwise you might end up with an empty file where there shouldn't be one.

All these different situations—appending, overwriting, reading without creating—are handled in C# using special file opening modes, which you set with the System.IO.FileMode enum. Each mode controls what happens when you open or create a file, letting you control exactly what goes down when you interact with files.

2. FileMode Enum—All the Options Explained Simply

Here are the main values of the FileMode enum:

Value Description Behavior if file exists Behavior if file doesn't exist
CreateNew
Creates a new file. If the file already exists—throws an exception Error OK, file is created
Create
Creates a new file if it doesn't exist, or overwrites the existing one Overwrites OK, creates
Open
Opens an existing file. If the file doesn't exist—exception OK, opens Error
OpenOrCreate
Opens if it exists, or creates a new one if it doesn't OK, opens OK, creates
Truncate
Opens an existing file and clears its length (content is deleted) OK, clears file Error
Append
Opens file for appending to the end, if it doesn't exist—creates a new one OK, adds to end OK, creates

Illustration: Behavior Scenarios

Behavior scenarios for different FileMode modes

3. Examples of Opening Files in Different Modes

Let's try all this out in practice with our mini-app we've been building throughout the course. Let's say we have a text file where we write greetings and the date of the entry. We'll look at three typical scenarios:

  • A. Creating a new file (CreateNew)
  • B. Overwriting a file (Create)
  • C. Appending lines to the end of a file (Append)

Creating a New File (FileMode.CreateNew)

If the file already exists, this mode guarantees you can't create it again: the program will throw an IOException. This is good if you can't afford to lose data or accidentally wipe someone else's files.

using System;
using System.IO;

string filePath = "greeting.txt";

// Let's try to create a new file—if it already exists, we'll get an exception!
try
{
    var stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
    var writer = new StreamWriter(stream);
    
    writer.WriteLine("Hello! This is the first entry.");
    writer.WriteLine($"Date: {DateTime.Now}");
    
    Console.WriteLine("File created successfully.");   
    writer.Close();
}
catch (IOException)
{
    Console.WriteLine($"File '{filePath}' already exists! We won't overwrite it.");
}

Heads up: if you run this code a second time—the catch will trigger, and your data won't get wiped.

Overwriting a File (FileMode.Create)

This mode doesn't mess around: if the file already exists, it'll be completely cleared. If not—it'll just create a new one. Handy when you want to start "with a clean slate" every time. For example, saving a report.

using System;
using System.IO;

string filePath = "greeting.txt";

// Create or fully overwrite the file
var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
var writer = new StreamWriter(stream);

writer.WriteLine("Hello! I completely updated the file :)");
writer.WriteLine($"Updated: {DateTime.Now}");

Console.WriteLine("File created or overwritten.");
writer.Close();

Run this code a few times—the file will always only have the latest lines you added. All the old stuff disappears without a trace.

Appending to the End of a File (FileMode.Append)

Awesome mode for logs, event journals, attendance tracking, etc. If the file doesn't exist—it gets created. If it does—data gets added to the end.

using System;
using System.IO;

string filePath = "greeting.txt";

// Add a new line to the end of the file
var stream = new FileStream(filePath, FileMode.Append, FileAccess.Write);
var writer = new StreamWriter(stream);

writer.WriteLine($"Another greeting! Date: {DateTime.Now}");

Console.WriteLine("Added a new line to the end of the file.");
writer.Close();

Try running this code a bunch of times in a row. The file will keep growing, each new entry will be at the very end.

4. How to Choose a File Opening Mode? Practical Tips

Real-life scenarios:

  • Logging: almost always use Append. Losing logs because of overwriting is a sysadmin's nightmare and a hacker's dream.
  • Exporting a report: usually Create is used, so you don't clutter up the folder with old versions.
  • Exporting data that's critical not to lose: here CreateNew is the way to go. If the file exists—error, don't touch anything.
  • Reading a file: you don't need a creation mode at all, use FileMode.Open—if the file doesn't exist, that's a problem you should know about.

When coding in C#, you often use static methods of the File class, which pick the right mode for you under the hood. For example, File.AppendAllText always uses Append, and File.WriteAllText uses Create.

5. File Modes and Gotchas

A few sneaky things:

If you open a file with FileMode.Create or FileMode.Truncate, all the content will be wiped. Be careful—accidental data loss has happened to not just students, but even seasoned programmers with tons of experience.

If you try to open a non-existent file with FileMode.Open or FileMode.Truncate, you'll get a FileNotFoundException. Don't forget to check that the file actually exists with File.Exists(path).

With Append mode you can only write. If you need to both read and write, check out other modes (OpenOrCreate + the right FileAccess).

Example: Reading and Writing

Sometimes you want to both read and write to a file (like, you opened a bank account—you want to deposit money and check your balance). Use FileMode.OpenOrCreate:

using System.IO;

string filePath = "balance.txt";

// Open file for reading and writing; if it doesn't exist—create it
var stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
// Now you can read and write

6. Handy Details

File Opening Modes

Decision diagram for picking a file opening mode

Summary Table for File Opening Modes

FileMode File Exists File DOESN'T Exist Data Access Deletes old content?
CreateNew
Exception Creates new Writes N/A
Create
Overwrites Creates new Writes Yes
Open
Opens Exception Reads/writes No
OpenOrCreate
Opens Creates new Reads/writes No
Truncate
Clears Exception Writes Yes
Append
Opens for writing at end Creates new Write only No (adds)

Comparison with High-Level File Methods

  • File.WriteAllText(path, text) → under the hood uses FileMode.Create, so the old file gets overwritten.
  • File.AppendAllText(path, text) → uses Append mode, everything gets added to the end.
  • File.ReadAllText(path) → opens the file for reading (FileMode.Open).

Sometimes these methods are enough, but working with FileStream and specifying the mode directly gives you full control over what's happening.

OS-Specific Stuff

A lot of devs forget that in Windows, a file that's open by another process for writing might not be available for opening again—trying to access it will throw an error. So it's super important to use the FileShare parameter right, to manage shared access to the file (we'll talk more about this in another lecture). Different OSes have different locking and permission mechanisms, but the concept of file opening modes is universal.

2
Task
C# SELF, level 35, lesson 4
Locked
Appending to the End of a File
Appending to the End of a File
1
Survey/quiz
Working with Files, level 35, lesson 4
Unavailable
Working with Files
Basics of working with files in C#
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION