DEV Community

Cover image for C# TextReader Tutorial: Read Text Files Easily with Real Examples
suraj kumar
suraj kumar

Posted on

C# TextReader Tutorial: Read Text Files Easily with Real Examples

In C#, working with files is a fundamental skill for developers. Whether you are building a desktop application, a web service, or a utility tool, reading data from text files is a common requirement. The TextReader class in C# TextReader provides a simple and efficient way to read characters from text files or other character-based input streams. In this tutorial, we will explore the TextReader class, understand its methods, and see practical examples of reading text files in real-world scenarios.

What is C# TextReader?

The TextReader class is an abstract class in the System.IO namespace. It provides a base class for reading characters from streams and supports reading from files, strings, or other sources. Because TextReader is abstract, you typically use its derived classes, most commonly StreamReader, which reads characters from byte streams, particularly from text files.

The key advantage of using TextReader is its ability to provide a uniform API for reading characters, lines, or the entire content of a file, making it easier to work with text-based data.

using System.IO;
Enter fullscreen mode Exit fullscreen mode

Key Methods of TextReader

TextReader provides several useful methods for reading text:

  1. Read() – Reads the next character from the input stream and returns it as an integer.
  2. ReadLine() – Reads a line of characters from the input stream and returns it as a string.
  3. ReadToEnd() – Reads all characters from the current position to the end of the stream.
  4. Peek() – Returns the next character without advancing the reader position.
  5. Close() – Closes the TextReader and releases any system resources.

Using StreamReader to Read Text Files

While TextReader itself is abstract, its derived class StreamReader is most commonly used to read files. Let's see how to read a text file using StreamReader.

Example 1: Read the Entire File

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "sample.txt";

        try
        {
            using (TextReader reader = new StreamReader(filePath))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine("File Content:");
                Console.WriteLine(content);
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"File not found: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We use StreamReader to read a file called sample.txt.
  • ReadToEnd() reads the complete content at once.
  • using ensures the reader is closed automatically, even if an exception occurs.

Example 2: Read File Line by Line

Reading files line by line is more memory-efficient, especially for large files.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "sample.txt";

        using (TextReader reader = new StreamReader(filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • ReadLine() reads one line at a time.
  • The loop continues until the end of the file (when ReadLine() returns null).

Example 3: Using Peek() to Inspect Characters

Sometimes, you might want to look ahead at the next character without consuming it.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "sample.txt";

        using (TextReader reader = new StreamReader(filePath))
        {
            while (reader.Peek() != -1) // Peek returns -1 if end of file
            {
                int nextChar = reader.Read();
                Console.Write((char)nextChar);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Peek() returns the next character without advancing the reader.
  • This is useful when you want to conditionally process characters.

Best Practices When Using TextReader

  1. Always use using blocks – This ensures that the reader is properly disposed and resources are released.
  2. Handle exceptions – Files might not exist, or permissions may be denied. Use try-catch blocks to handle exceptions.
  3. Choose the right method – Use ReadLine() for large files to save memory; ReadToEnd() is convenient for small files.
  4. Encoding awarenessStreamReader allows specifying the file encoding if needed.
using (TextReader reader = new StreamReader(filePath, Encoding.UTF8))
{
    string content = reader.ReadToEnd();
}
Enter fullscreen mode Exit fullscreen mode

Real-World Example: Reading a CSV File

Suppose you have a CSV file with user data:

Name,Age,Email
Alice,25,alice@example.com
Bob,30,bob@example.com
Charlie,28,charlie@example.com
Enter fullscreen mode Exit fullscreen mode

You can read and process it using TextReader:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "users.csv";

        using (TextReader reader = new StreamReader(filePath))
        {
            string header = reader.ReadLine(); // Skip header

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] fields = line.Split(',');
                Console.WriteLine($"Name: {fields[0]}, Age: {fields[1]}, Email: {fields[2]}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • ReadLine() reads each row.
  • Split(',') separates values.
  • This is a practical way to handle CSV files using TextReader.

Conclusion

The C# TextReader class in C# is a versatile and essential tool for reading text-based input. Whether you are working with small configuration files, large logs, or CSV data, TextReader and its derived class StreamReader make reading text files simple and efficient. Remember to follow best practices, such as using using statements, handling exceptions, and choosing the appropriate reading method based on your file size and requirements.

Mastering TextReader is a fundamental skill for any C# developer and provides a strong foundation for working with file I/O operations in real-world applications.

Top comments (0)