C# ยท Chapter 42 of 46

C# Files

C# provides classes like File and StreamWriter/StreamReader in the System.IO namespace to read from and write to files on disk.

Working with files is important for tasks like saving user data, reading configuration, or processing logs. Always handle exceptions when working with files, since issues like missing files or permission errors can occur.

Syntax
File.WriteAllText(path, content);
string text = File.ReadAllText(path);

Writing to files

File.WriteAllText() writes a string to a file, creating it if it doesn't exist or overwriting it if it does. File.AppendAllText() adds text to the end of an existing file.

Reading from files

File.ReadAllText() reads an entire file's contents into a string, and File.ReadAllLines() reads it into an array of lines, useful for processing line by line.

Example 1 (csharp)
using System;
using System.IO;

class Program {
  static void Main() {
    File.WriteAllText("greeting.txt", "Hello, File!");
    string content = File.ReadAllText("greeting.txt");
    Console.WriteLine(content);
  }
}
Output
Hello, File!

The text is written to greeting.txt and then read back and printed.

Example 2 (csharp)
using System;
using System.IO;

class Program {
  static void Main() {
    try {
      string content = File.ReadAllText("missing.txt");
      Console.WriteLine(content);
    } catch (FileNotFoundException) {
      Console.WriteLine("File not found.");
    }
  }
}
Output
File not found.

Trying to read a nonexistent file throws a FileNotFoundException, which is caught gracefully.

Key points

  • System.IO provides classes for file operations in C#.
  • File.WriteAllText() and File.ReadAllText() handle simple text file I/O.
  • File.AppendAllText() adds text without overwriting existing content.
  • Always handle exceptions when working with files, since they can fail in many ways.
๐Ÿ’ก Note: For very large files, use StreamReader/StreamWriter to process data line by line instead of loading everything into memory at once.

๐Ÿ“ Quick Quiz

1. Which namespace provides file handling classes in C#?

2. Which method reads an entire file into a single string?

3. What exception is thrown when reading a file that doesn't exist?