C# Files

Reading and writing files in C#

📁 What is File Handling?

File handling in C# allows you to create, read, write, and manipulate files on your computer. The System.IO namespace provides classes for working with files and directories efficiently.


using System;
using System.IO;

// Write to a file
File.WriteAllText("test.txt", "Hello, World!");

// Read from a file
string content = File.ReadAllText("test.txt");
Console.WriteLine(content);
                                    

Output:

Hello, World!

Key File Operations

✍️

Write Files

Create and write content to files

File.WriteAllText(
    "file.txt", "text");
📖

Read Files

Read content from files

string text = 
File.ReadAllText("file.txt");

Append Files

Add content to existing files

File.AppendAllText(
    "file.txt", "more");
🗑️

Delete Files

Remove files from disk

File.Delete(
    "file.txt");

🔹 Writing to Files

C# offers streamlined static methods like File.WriteAllText and File.AppendAllText for simple file writing tasks. WriteAllText creates a new file or completely overwrites an existing one with the provided string content. AppendAllText safely adds text to the end of a file, creating it if it doesn't exist. These are perfect for configuration files, logs, or data dumps. For more control over the writing process (like writing incrementally), the StreamWriter class is the recommended tool.

using System;
using System.IO;

class Program {
    static void Main() {
        string path = "myfile.txt";
        
        // Write to file (overwrites if exists)
        File.WriteAllText(path, "First line\n");
        Console.WriteLine("File created and written");
        
        // Append to file
        File.AppendAllText(path, "Second line\n");
        File.AppendAllText(path, "Third line\n");
        Console.WriteLine("Content appended");
        
        // Read and display
        string content = File.ReadAllText(path);
        Console.WriteLine("\nFile content:");
        Console.WriteLine(content);
    }
}

Output:

File created and written

Content appended


File content:

First line

Second line

Third line

🔹 Reading from Files

Reading file content can be done in bulk or line-by-line using File.ReadAllText and File.ReadAllLines. ReadAllText returns the entire file as a single string, ideal for smaller files like JSON configs. ReadAllLines returns a string array where each element is a line, perfect for processing structured data like CSVs. For memory efficiency with large files, use StreamReader to read incrementally. Always wrap file reading in try-catch blocks to handle potential IOException or FileNotFoundException.

using System;
using System.IO;

class Program {
    static void Main() {
        string path = "data.txt";
        
        // Create sample file
        File.WriteAllText(path, "Apple\nBanana\nCherry\nDate");
        
        // Read entire file
        string allText = File.ReadAllText(path);
        Console.WriteLine("All content:");
        Console.WriteLine(allText);
        
        Console.WriteLine("\nLine by line:");
        // Read line by line
        string[] lines = File.ReadAllLines(path);
        foreach (string line in lines) {
            Console.WriteLine($"- {line}");
        }
    }
}

Output:

All content:

Apple

Banana

Cherry

Date


Line by line:

- Apple

- Banana

- Cherry

- Date

🔹 Checking File Existence

Always verify a file's existence with File.Exists before attempting operations to avoid runtime exceptions. This method returns a boolean and is a lightweight check. However, note that a file could be deleted or locked between the check and the subsequent operation (a "Time-of-check to time-of-use" race condition). Therefore, robust code still requires try-catch blocks around the actual file operation. This pattern is crucial for creating user-friendly applications that guide users instead of crashing on missing files.

using System;
using System.IO;

class Program {
    static void Main() {
        string path = "config.txt";
        
        if (File.Exists(path)) {
            Console.WriteLine("File exists!");
            string content = File.ReadAllText(path);
            Console.WriteLine($"Content: {content}");
        } else {
            Console.WriteLine("File not found. Creating new file...");
            File.WriteAllText(path, "Default configuration");
            Console.WriteLine("File created successfully!");
        }
        
        // Check again
        if (File.Exists(path)) {
            Console.WriteLine($"File now exists at: {Path.GetFullPath(path)}");
        }
    }
}

Output:

File not found. Creating new file...

File created successfully!

File now exists at: C:\Projects\config.txt

🔹 Using StreamWriter and StreamReader

StreamWriter and StreamReader provide granular, efficient control for sequential file I/O operations. Unlike the static File methods, they allow you to open a stream, write or read pieces of data over time, and close it explicitly, which is memory-efficient for large files. They support different encodings and can be wrapped in using statements for automatic disposal. This makes them the preferred choice for writing logs, processing large datasets line-by-line, or building custom file parsers.

using System;
using System.IO;

class Program {
    static void Main() {
        string path = "log.txt";
        
        // Write using StreamWriter
        using (StreamWriter writer = new StreamWriter(path)) {
            writer.WriteLine("Log started");
            writer.WriteLine("Processing data...");
            writer.WriteLine("Task completed");
        }
        Console.WriteLine("Log file written");
        
        // Read using StreamReader
        Console.WriteLine("\nReading log:");
        using (StreamReader reader = new StreamReader(path)) {
            string line;
            while ((line = reader.ReadLine()) != null) {
                Console.WriteLine($"[LOG] {line}");
            }
        }
    }
}

Output:

Log file written


Reading log:

[LOG] Log started

[LOG] Processing data...

[LOG] Task completed

🔹 File Information and Operations

The File.Copy() and File.Delete() methods handle fundamental file operations in C#. File.Copy(source, destination) creates a duplicate of a file at a specified path, preserving the original data. File.Delete(path) permanently removes a file from the storage system. These operations are essential for file management tasks, such as backing up documents (document_copy.txt) or cleaning up temporary files, ensuring data is either safely replicated or removed as required.

using System;
using System.IO;

class Program {
    static void Main() {
        string path = "document.txt";
        File.WriteAllText(path, "Sample document content");
        
        FileInfo fileInfo = new FileInfo(path);
        
        Console.WriteLine("File Information:");
        Console.WriteLine($"Name: {fileInfo.Name}");
        Console.WriteLine($"Size: {fileInfo.Length} bytes");
        Console.WriteLine($"Created: {fileInfo.CreationTime}");
        Console.WriteLine($"Extension: {fileInfo.Extension}");
        Console.WriteLine($"Read-only: {fileInfo.IsReadOnly}");
        
        // Copy file
        string copyPath = "document_copy.txt";
        fileInfo.CopyTo(copyPath);
        Console.WriteLine($"\nFile copied to {copyPath}");
        
        // Delete original
        File.Delete(path);
        Console.WriteLine("Original file deleted");
    }
}

Output:

File Information:

Name: document.txt

Size: 24 bytes

Created: 10/3/2025 10:30:00 AM

Extension: .txt

Read-only: False


File copied to document_copy.txt

Original file deleted

🧠 Test Your Knowledge

Which method reads all text from a file at once?