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.
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.
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);
}
}Hello, File!The text is written to greeting.txt and then read back and printed.
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.");
}
}
}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.
