Let’s go through reading and writing text files in C# using StreamReader and StreamWriter β€” the standard way to handle text files.


πŸ“Œ 1. StreamWriter: Writing Text Files

  • StreamWriter is used to write text to a file

  • Can create a new file or overwrite/append to an existing file

Basic Syntax

using System.IO;
 
string path = "example.txt";
 
using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("Hello, World!");
    writer.WriteLine("This is a text file.");
}
  • using ensures the file is properly closed after writing

  • WriteLine writes a line with newline, Write writes without newline

Append Mode

using (StreamWriter writer = new StreamWriter(path, append: true))
{
    writer.WriteLine("Adding a new line.");
}

πŸ“Œ 2. StreamReader: Reading Text Files

  • StreamReader is used to read text from a file

  • Can read line by line or the entire file

Read Entire File

using (StreamReader reader = new StreamReader(path))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}

Read Line by Line

using (StreamReader reader = new StreamReader(path))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

πŸ“Œ 3. File.Exists Check

  • Always good practice to check if file exists before reading:
if (File.Exists(path))
{
    using (StreamReader reader = new StreamReader(path))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
else
{
    Console.WriteLine("File not found!");
}

πŸ“Œ 4. Other Useful Methods

Method / ClassPurpose
File.ReadAllText()Reads entire file in one call
File.ReadAllLines()Reads all lines into a string array
File.WriteAllText()Writes entire string to file (overwrites)
File.AppendAllText()Appends text to a file

πŸ“Œ 5. Example: Writing & Reading Together

string filePath = "data.txt";
 
// Write to file
using (StreamWriter writer = new StreamWriter(filePath))
{
    writer.WriteLine("Alice,25");
    writer.WriteLine("Bob,30");
}
 
// Read from file
using (StreamReader reader = new StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        string[] parts = line.Split(',');
        Console.WriteLine($"Name: {parts[0]}, Age: {parts[1]}");
    }
}

Output:

Name: Alice, Age: 25
Name: Bob, Age: 30

πŸ“Œ 6. Best Practices

  1. Use using blocks to automatically close streams

  2. Handle exceptions (e.g., FileNotFoundException, IOException)

  3. Use File.Exists before reading

  4. Prefer File.ReadAllText / WriteAllText for small files for simplicity


βœ… Tip:

  • Use StreamReader/StreamWriter for large files where line-by-line processing is needed

  • Use File.ReadAllText / WriteAllText for small files