C# FileMode Enum
last modified April 20, 2025
This tutorial explains how to use the FileMode enum in C# to control file creation and opening behavior. FileMode specifies how the operating system should open a file.
The FileMode enum is used with FileStream and other file-related classes to determine how to open or create a file. It provides six options that control file access behavior.
Understanding FileMode is essential for proper file handling in C#. It determines whether to create new files, open existing ones, or append to files. The enum values work with FileAccess and FileShare enums for complete file control.
FileMode.Create Example
FileMode.Create specifies that the operating system should create a new file. If the file exists, it will be overwritten.
using System; using System.IO; class Program { static void Main() { string path = "test1.txt"; using (FileStream fs = new FileStream(path, FileMode.Create)) { Console.WriteLine($"File created at: {path}"); // Write some data byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileMode.Create!"); fs.Write(data, 0, data.Length); } // Verify file exists Console.WriteLine($"File exists: {File.Exists(path)}"); } }
This example creates a new file or overwrites an existing one. The FileMode.Create flag ensures the file is created if it doesn't exist. If the file exists, its contents are truncated to zero bytes.
After creating the FileStream, we write some UTF-8 encoded text to the file. The using statement ensures proper disposal of resources. Finally, we verify the file exists using File.Exists.
FileMode.CreateNew Example
FileMode.CreateNew specifies that the operating system should create a new file. If the file exists, an IOException is thrown.
using System; using System.IO; class Program { static void Main() { string path = "test2.txt"; try { using (FileStream fs = new FileStream(path, FileMode.CreateNew)) { Console.WriteLine($"New file created at: {path}"); // Write some data byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileMode.CreateNew!"); fs.Write(data, 0, data.Length); } } catch (IOException ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
This example attempts to create a new file. If the file already exists, an IOException is thrown. This behavior differs from FileMode.Create, which would overwrite the existing file.
The try-catch block handles potential IOExceptions. This mode is useful when you need to ensure you're not accidentally overwriting an existing file. It provides atomic file creation with safety against overwrites.
FileMode.Open Example
FileMode.Open specifies that the operating system should open an existing file. If the file doesn't exist, a FileNotFoundException is thrown.
using System; using System.IO; class Program { static void Main() { string path = "test3.txt"; // First create the file File.WriteAllText(path, "Existing content"); try { using (FileStream fs = new FileStream(path, FileMode.Open)) { Console.WriteLine($"File opened successfully: {path}"); // Read the file content byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string content = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine($"Content: {content}"); } } catch (FileNotFoundException ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
This example first creates a file, then opens it with FileMode.Open. The FileStream reads the existing content. If the file didn't exist, the operation would fail with FileNotFoundException.
The example demonstrates safe file opening for reading existing content. FileMode.Open is ideal when you need to work with existing files and want to fail explicitly if the file doesn't exist rather than creating a new one.
FileMode.OpenOrCreate Example
FileMode.OpenOrCreate specifies that the operating system should open a file if it exists; otherwise, a new file should be created.
using System; using System.IO; class Program { static void Main() { string path = "test4.txt"; using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { if (fs.Length == 0) { Console.WriteLine($"New file created at: {path}"); byte[] data = System.Text.Encoding.UTF8.GetBytes("New content"); fs.Write(data, 0, data.Length); } else { Console.WriteLine($"Existing file opened: {path}"); // Read and display existing content byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string content = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine($"Existing content: {content}"); } } } }
This example checks if the file exists. If it does, it opens it; otherwise, it creates a new file. The file length is used to determine if the file was newly created or already existed.
FileMode.OpenOrCreate is useful when you want to work with a file whether it exists or not, but don't want to truncate existing content like FileMode.Create would. It's a safe option for file operations where you're not sure if the file exists.
FileMode.Truncate Example
FileMode.Truncate specifies that the operating system should open an existing file and truncate its size to zero bytes.
using System; using System.IO; class Program { static void Main() { string path = "test5.txt"; // First create a file with content File.WriteAllText(path, "This content will be truncated"); try { using (FileStream fs = new FileStream(path, FileMode.Truncate)) { Console.WriteLine($"File truncated: {path}"); // Verify file is empty Console.WriteLine($"File length after truncate: {fs.Length}"); // Write new content byte[] data = System.Text.Encoding.UTF8.GetBytes("New content after truncate"); fs.Write(data, 0, data.Length); } } catch (FileNotFoundException ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
This example first creates a file with content, then opens it with FileMode.Truncate. The existing content is erased (file size becomes 0), and new content can be written. If the file doesn't exist, an exception is thrown.
FileMode.Truncate is useful when you need to completely overwrite an existing file's content. Unlike FileMode.Create, it requires the file to exist first. This mode preserves file attributes while clearing content.
FileMode.Append Example
FileMode.Append opens an existing file and seeks to the end of it, or creates a new file. This mode can only be used with write-only access.
using System; using System.IO; class Program { static void Main() { string path = "test6.txt"; // First write initial content File.WriteAllText(path, "Initial line\n"); using (FileStream fs = new FileStream(path, FileMode.Append)) { // Append new content byte[] data = System.Text.Encoding.UTF8.GetBytes("Appended line\n"); fs.Write(data, 0, data.Length); Console.WriteLine($"Content appended to: {path}"); } // Display final content Console.WriteLine("Final content:"); Console.WriteLine(File.ReadAllText(path)); } }
This example demonstrates appending content to a file. The initial content is written first, then additional content is appended using FileMode.Append. The file pointer is automatically positioned at the end of the file.
FileMode.Append is specifically designed for adding content to the end of files. It's more efficient than manually seeking to the end when you only need to append data. Note that with this mode, you can't read from the file.
Combining FileMode with FileAccess
FileMode can be combined with FileAccess to specify both how to open the file and what operations are permitted. This example shows the combination.
using System; using System.IO; class Program { static void Main() { string path = "test7.txt"; // Create a file with read/write access using (FileStream fs = new FileStream( path, FileMode.Create, FileAccess.ReadWrite)) { // Write data byte[] data = System.Text.Encoding.UTF8.GetBytes("Initial content"); fs.Write(data, 0, data.Length); // Reset position to read fs.Position = 0; // Read data back byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string content = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine($"Read content: {content}"); } // Open same file with read-only access using (FileStream fs = new FileStream( path, FileMode.Open, FileAccess.Read)) { Console.WriteLine("\nOpened file in read-only mode"); // Attempting to write would throw NotSupportedException try { byte[] data = System.Text.Encoding.UTF8.GetBytes("New content"); fs.Write(data, 0, data.Length); } catch (NotSupportedException ex) { Console.WriteLine($"Expected error when writing: {ex.Message}"); } } } }
This example first creates a file with read/write access, writes content, then reads it back. Then it opens the same file in read-only mode and demonstrates that writing is not allowed.
Combining FileMode with FileAccess provides precise control over file operations. FileAccess.ReadWrite allows both reading and writing, FileAccess.Read provides read-only access, and FileAccess.Write provides write-only access. This combination is essential for secure file handling.
Source
This tutorial covered the FileMode enum in C#, demonstrating all six enum values with practical examples. Understanding these modes is essential for proper file handling in .NET applications.
Author
List all C# tutorials.