C# FileAccess Enum
last modified April 20, 2025
This tutorial explains how to use the FileAccess enum in C# to control file access permissions. FileAccess specifies read, write, or read/write access to a file.
The FileAccess enum is part of the System.IO namespace. It defines constants for read, write, or read/write access to a file. These permissions are used when opening files with FileStream or similar classes.
FileAccess
helps ensure proper file handling by explicitly
declaring intended access patterns. This prevents accidental modifications
and improves security in file operations.
Basic FileAccess Example
This example demonstrates opening a file with read-only access using FileAccess.Read. We'll read the contents of a text file.
using System; using System.IO; using System.Text; class Program { static void Main() { string path = "example.txt"; File.WriteAllText(path, "Hello FileAccess!"); using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (var reader = new StreamReader(fs, Encoding.UTF8)) { string content = reader.ReadToEnd(); Console.WriteLine(content); } } }
The code creates a file with write access, then opens it with read-only permissions. The FileStream constructor takes FileAccess.Read as the third parameter. This ensures the file can only be read, not modified.
The StreamReader reads the entire file content. Attempting to write to this stream would throw an exception. This demonstrates how FileAccess enforces access restrictions at the stream level.
Writing to a File with FileAccess.Write
This example shows how to open a file with write-only access using FileAccess.Write. We'll append text to an existing file.
using System; using System.IO; using System.Text; class Program { static void Main() { string path = "log.txt"; using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write)) using (var writer = new StreamWriter(fs, Encoding.UTF8)) { writer.WriteLine($"{DateTime.Now}: Log entry added"); } Console.WriteLine("Log entry written successfully"); } }
The FileStream is opened with FileAccess.Write permission in append mode. This allows writing to the file but prevents reading from it. The StreamWriter adds a timestamped log entry.
Attempting to read from this stream would throw an exception. This demonstrates how FileAccess.Write restricts operations to writing only. It's useful for log files where you only need to append data.
Read/Write Access with FileAccess.ReadWrite
This example demonstrates full read/write access using FileAccess.ReadWrite. We'll modify a configuration file in place.
using System; using System.IO; class Program { static void Main() { string path = "config.dat"; File.WriteAllText(path, "Initial configuration"); using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) { // Read existing content byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string content = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine("Original: " + content); // Modify content fs.Position = 0; string newContent = "Modified configuration"; byte[] newData = System.Text.Encoding.UTF8.GetBytes(newContent); fs.Write(newData, 0, newData.Length); fs.SetLength(newData.Length); } Console.WriteLine("File updated successfully"); } }
The file is opened with FileAccess.ReadWrite, allowing both reading and writing operations. We first read the existing content, then overwrite it with new data. The Position property resets to the start for writing.
FileAccess.ReadWrite is useful when you need to both read and modify a file's contents. The example shows how to properly handle the file position when switching between read and write operations.
Combining FileAccess with FileShare
This example shows how to combine FileAccess with FileShare to control how files can be accessed by other processes. We'll create a file with shared read access.
using System; using System.IO; class Program { static void Main() { string path = "shared.txt"; using (var fs = new FileStream( path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) { // Write initial data byte[] data = System.Text.Encoding.UTF8.GetBytes("Shared content"); fs.Write(data, 0, data.Length); // Simulate another process reading the file try { using (var sharedFs = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read)) { Console.WriteLine("File opened successfully in another process"); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } }
The FileStream is created with FileAccess.ReadWrite and FileShare.Read. This allows other processes to open the file for reading but not for writing. The example simulates another process accessing the file.
The combination of FileAccess and FileShare provides fine-grained control over file sharing in multi-process scenarios. This is particularly useful for applications that need to coordinate file access between processes.
Handling Access Denied Errors
This example demonstrates proper error handling when file access is denied. We'll attempt to open a file with conflicting permissions.
using System; using System.IO; class Program { static void Main() { string path = "locked.txt"; File.WriteAllText(path, "Test content"); // First process locks the file using (var lockedFs = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.None)) { Console.WriteLine("File locked by first process"); try { // Second process tries to access using (var fs = new FileStream( path, FileMode.Open, FileAccess.Read)) { Console.WriteLine("This won't be reached"); } } catch (UnauthorizedAccessException ex) { Console.WriteLine("Access denied: " + ex.Message); } catch (IOException ex) { Console.WriteLine("IO Error: " + ex.Message); } } } }
The first FileStream opens the file with FileShare.None, preventing other
access. The second attempt to open the file throws an exception. We catch
both UnauthorizedAccessException
and IOException
for robust error handling.
This example shows how to properly handle access conflicts in real-world applications. The try-catch blocks ensure the application can gracefully recover from access denied situations.
FileAccess with BinaryReader/Writer
This example demonstrates using FileAccess with BinaryReader and BinaryWriter for efficient binary file operations.
using System; using System.IO; class Program { static void Main() { string path = "data.bin"; // Write binary data using (var fs = new FileStream( path, FileMode.Create, FileAccess.Write)) using (var writer = new BinaryWriter(fs)) { writer.Write(42); writer.Write(3.14159); writer.Write(true); } // Read binary data using (var fs = new FileStream( path, FileMode.Open, FileAccess.Read)) using (var reader = new BinaryReader(fs)) { int number = reader.ReadInt32(); double pi = reader.ReadDouble(); bool flag = reader.ReadBoolean(); Console.WriteLine($"Read: {number}, {pi}, {flag}"); } } }
The binary file is first created with write-only access, then opened with read-only access. BinaryWriter and BinaryReader work with the specified FileAccess permissions. This ensures proper access control for binary files.
The example shows how FileAccess integrates seamlessly with binary file operations. The separation of write and read operations demonstrates clean access pattern separation.
Asynchronous File Operations with FileAccess
This example shows how to use FileAccess with asynchronous file operations for better performance in I/O-bound applications.
using System; using System.IO; using System.Threading.Tasks; class Program { static async Task Main() { string path = "async.txt"; // Asynchronous write using (var fs = new FileStream( path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous)) using (var writer = new StreamWriter(fs)) { await writer.WriteLineAsync("Asynchronous line 1"); await writer.WriteLineAsync("Asynchronous line 2"); } // Asynchronous read using (var fs = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous)) using (var reader = new StreamReader(fs)) { string content = await reader.ReadToEndAsync(); Console.WriteLine("File content:"); Console.WriteLine(content); } } }
The FileStream is configured for asynchronous operations with FileOptions. FileAccess controls the access type while the operations execute asynchronously. This combines access control with performance benefits.
The example demonstrates modern async/await patterns with FileAccess. Asynchronous I/O is particularly valuable for applications handling large files or many concurrent operations.
Source
This tutorial covered using the FileAccess enum in C# to control file permissions, including read, write, and read/write operations with various file handling classes.
Author
List all C# tutorials.