File Handling: Reading/Writing .txt Files in C#

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 .txt file 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

ConceptPurpose
File.ReadAllTextQuickly read entire file as a string
File.ReadAllLinesRead file into a string array (lines)
File.WriteAllTextWrite text, overwrite file
File.AppendAllTextAppend text to existing file
StreamReaderRead file line-by-line with control
StreamWriterWrite 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.