Working with files is a fundamental skill for many C# applications โ whether saving user data, loading configurations, or processing logs. This session covers how to read from and write to plain text files (.txt) safely and efficiently using C#.
Youโll get hands-on with the most common file operations and understand best practices to avoid common pitfalls.
๐ What Is File Handling?
File handling means working with files on disk โ opening, reading, writing, and closing them โ to persist data beyond the lifetime of a program.
๐น Reading Text Files
The easiest way to read a text file in C# is using File.ReadAllText() or File.ReadAllLines():
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
string[] lines = File.ReadAllLines("example.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
๐ธ Writing Text Files
To write text to a file, use File.WriteAllText() or File.AppendAllText():
string textToWrite = "Hello, this is a test.";
File.WriteAllText("output.txt", textToWrite); // Overwrites existing content
File.AppendAllText("output.txt", "\nAppending this line."); // Adds to file
โ๏ธ Working with Streams for Large Files or More Control
For reading/writing large files or streaming data, use StreamReader and StreamWriter:
using (StreamReader reader = new StreamReader("example.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("Writing line by line.");
writer.WriteLine("Another line.");
}
๐ง Why Learn File Handling?
- Enables data persistence between program runs
- Useful for logs, configs, reports, and more
- Foundation for more advanced file/database operations
๐งช Practice Exercise
Create a program that:
- Reads a
.txtfile line by line and counts the number of words per line - Writes the word counts to a new output file
- Handles missing file exceptions gracefully
๐ Summary
| Concept | Purpose |
|---|---|
| File.ReadAllText | Quickly read entire file as a string |
| File.ReadAllLines | Read file into a string array (lines) |
| File.WriteAllText | Write text, overwrite file |
| File.AppendAllText | Append text to existing file |
| StreamReader | Read file line-by-line with control |
| StreamWriter | Write text line-by-line with control |
๐ฌ Want help applying file handling in your projects or need examples for complex scenarios? Reach out โ Iโm here to help you master professional C# file operations.