Home C# TextReader in C# tutorial

TextReader in C# tutorial

TextReader in C# is an abstract base class that provides methods for reading text data from streams.

It’s part of the System.IO namespace and serves as a base class for derived classes like StreamReader (for reading from files) and StringReader (for reading from strings).

In this tutorial, we’ll cover:

1. Basics of TextReader

TextReader provides foundational methods for reading character data. Since it is an abstract class, you cannot instantiate TextReader directly, but you can use its derived classes like StreamReader and StringReader. The class includes methods such as Read(), ReadLine(), and ReadToEnd().

Common TextReader Methods:

  • Read(): Reads a single character and returns its integer value.
  • ReadLine(): Reads a line of characters.
  • ReadToEnd(): Reads all remaining characters from the current position to the end of the stream.

2. Reading Text from a File with StreamReader

StreamReader, derived from TextReader, is designed for reading text files. It provides efficient methods for reading lines or entire files.

Example: Reading a Text File Line by Line

using System;
using System.IO;

public class StreamReaderExample
{
    public static void Main()
    {
        using (TextReader reader = new StreamReader("sample.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Explanation:

  • StreamReader is used to read from sample.txt.
  • ReadLine() reads each line in the file until the end of the file is reached, at which point it returns null.

Output (based on contents of sample.txt):

This is the first line.
This is the second line.
This is the third line.

3. Reading Text from a String with StringReader

StringReader, another derived class of TextReader, allows reading from an in-memory string. This is useful for parsing text that isn’t in a file.

Example: Reading Text from a String

using System;
using System.IO;

public class StringReaderExample
{
    public static void Main()
    {
        string text = "This is the first line.\nThis is the second line.\nThis is the third line.";
        
        using (TextReader reader = new StringReader(text))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Explanation:

  • StringReader reads the provided string as if it were a file.
  • Each call to ReadLine() returns one line from the string until all lines are read.

Output:

This is the first line.
This is the second line.
This is the third line.

4. Using TextReader Methods (Read, ReadLine, ReadToEnd)

TextReader provides multiple ways to read data, including Read() for reading a single character, ReadLine() for reading a single line, and ReadToEnd() for reading the entire content.

Example: Reading a Single Character

using System;
using System.IO;

public class TextReaderReadExample
{
    public static void Main()
    {
        using (TextReader reader = new StringReader("Hello"))
        {
            int character;
            while ((character = reader.Read()) != -1) // -1 indicates end of the stream
            {
                Console.Write((char)character + " ");
            }
        }
    }
}

Explanation:

  • Read() reads a single character at a time, returning its ASCII value.
  • The loop continues until Read() returns -1, indicating the end of the stream.

Output:

H e l l o

Example: Reading All Text at Once

using System;
using System.IO;

public class TextReaderReadToEndExample
{
    public static void Main()
    {
        using (TextReader reader = new StreamReader("sample.txt"))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine("File content:\n" + content);
        }
    }
}

Explanation:

  • ReadToEnd() reads the entire content of the file in a single string.
  • This approach is useful for small files where reading the entire content into memory is feasible.

Output (based on contents of sample.txt):

File content:
This is the first line.
This is the second line.
This is the third line.

5. Practical Example: Parsing a CSV File

TextReader can be used to read and parse structured data formats like CSV files. Here’s an example of reading a CSV file line by line and splitting each line into fields.

Example: Parsing a CSV File

using System;
using System.IO;

public class CsvReaderExample
{
    public void ReadCsv(string filePath)
    {
        using (TextReader reader = new StreamReader(filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] columns = line.Split(',');
                Console.WriteLine($"ID: {columns[0]}, Name: {columns[1]}, Age: {columns[2]}");
            }
        }
    }
}

public class CsvExample
{
    public static void Main()
    {
        CsvReaderExample csvReader = new CsvReaderExample();
        csvReader.ReadCsv("data.csv");
    }
}

Explanation:

  • Each line is read from the CSV file using ReadLine().
  • line.Split(‘,') splits each line by commas, creating an array of columns.
  • Each column is printed in a structured format.

Content in data.csv:

1,John Doe,30
2,Jane Smith,25
3,Bob Johnson,35

Output:

ID: 1, Name: John Doe, Age: 30
ID: 2, Name: Jane Smith, Age: 25
ID: 3, Name: Bob Johnson, Age: 35

Advanced Example: Skipping Empty Lines with TextReader

To handle files with empty lines or whitespace-only lines, use string.IsNullOrWhiteSpace() to skip those lines.

Example: Reading and Skipping Empty Lines

using System;
using System.IO;

public class TextReaderSkipEmptyLinesExample
{
    public static void Main()
    {
        using (TextReader reader = new StreamReader("sample_with_empty_lines.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (string.IsNullOrWhiteSpace(line))
                    continue; // Skip empty or whitespace-only lines

                Console.WriteLine("Read line: " + line);
            }
        }
    }
}

Explanation:

  • string.IsNullOrWhiteSpace(line) checks if a line is empty or contains only whitespace and skips it.
  • Non-empty lines are printed.

Sample content in sample_with_empty_lines.txt:

This is the first line.

This is the second line.


This is the third line.

Output:

Read line: This is the first line.
Read line: This is the second line.
Read line: This is the third line.

Summary

TextReader in C# is an essential class for reading character data efficiently, whether it’s from a file, a string, or another source.

Here’s a recap of the main points:

  • Basic Setup: TextReader provides foundational methods for reading character-based data.
  • Reading from a File: StreamReader, derived from TextReader, is designed for reading text files.
  • Reading from a String: StringReader allows reading character data directly from strings.
  • Key Methods:
    • Read(): Reads one character at a time.
    • ReadLine(): Reads one line at a time.
    • ReadToEnd(): Reads the entire content in one go.
  • Practical Applications: TextReader is ideal for parsing structured data formats like CSV files.

Using TextReader and its derived classes allows for efficient, flexible text data reading in C# applications.

 

You may also like