Home C# StreamReader in C# tutorial

StreamReader in C# tutorial

StreamReader in C# is a class that provides methods for reading characters from a stream in a particular encoding.

It is designed for reading text files and offers methods for reading individual lines, entire files, and blocks of characters efficiently.

In this tutorial, we’ll cover:

1. Basics of StreamReader

StreamReader is part of the System.IO namespace and is generally used for reading text files. It supports multiple encodings and allows reading line by line, character by character, or an entire file at once.

Syntax for Basic StreamReader Setup:

using System.IO;

using (StreamReader reader = new StreamReader("file.txt"))
{
    // Reading code goes here
}

The using statement ensures that the file is automatically closed when reading is done, preventing resource leaks.

2. Reading a Text File Line by Line

The ReadLine() method is commonly used to read text files line by line. This is efficient for large files where loading the entire file into memory might be impractical.

Example: Reading a Text File Line by Line

using System;
using System.IO;

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

Explanation:

  • The while loop reads each line until the end of the file is reached.
  • ReadLine() returns null when there are no more lines to read, which stops the loop.

Output (based on contents of sample.txt):

Line 1 of sample text.
Line 2 of sample text.
Line 3 of sample text.

3. Reading an Entire File at Once

To read the entire file at once, use ReadToEnd(). This is useful for smaller files where loading everything into memory is feasible.

Example: Reading an Entire File at Once

using System;
using System.IO;

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

Explanation:

  • ReadToEnd() reads the entire file’s content into a single string.
  • This is suitable for smaller files, as large files could consume a lot of memory.

Output (based on contents of sample.txt):

File content:
Line 1 of sample text.
Line 2 of sample text.
Line 3 of sample text.

4. Reading Specific Parts of a File

To read a specific number of characters from a file, use the Read(char[], int, int) method, which reads a specified number of characters into a buffer.

Example: Reading a Specific Number of Characters

using System;
using System.IO;

public class StreamReaderReadExample
{
    public static void Main()
    {
        using (StreamReader reader = new StreamReader("sample.txt"))
        {
            char[] buffer = new char[20]; // Buffer to hold characters
            int bytesRead = reader.Read(buffer, 0, buffer.Length);

            Console.WriteLine("Characters read: " + new string(buffer, 0, bytesRead));
        }
    }
}

Explanation:

  • A buffer of 20 characters is created.
  • reader.Read(buffer, 0, buffer.Length) reads up to 20 characters and stores them in the buffer.
  • new string(buffer, 0, bytesRead) converts the buffer to a string for output.

Output:

Characters read: Line 1 of sample tex

5. Using StreamReader with Different Encodings

By default, StreamReader uses UTF-8 encoding, but you can specify a different encoding as needed, such as ASCII, Unicode, or UTF-32.

Example: Reading with a Different Encoding (UTF-32)

using System;
using System.IO;
using System.Text;

public class StreamReaderEncodingExample
{
    public static void Main()
    {
        using (StreamReader reader = new StreamReader("utf32_sample.txt", Encoding.UTF32))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine("Content read with UTF-32 encoding:\n" + content);
        }
    }
}

Explanation:

  • Encoding.UTF32 specifies that the file should be read using UTF-32 encoding.
  • This is useful when working with text files containing non-ASCII characters or files saved in different encodings.

Output (based on contents of utf32_sample.txt):

Content read with UTF-32 encoding:
This is text encoded in UTF-32.

6. Practical Example: Reading CSV Data

StreamReader is often used to read structured data formats like CSV (Comma-Separated Values) files. Here’s how you can read and parse a CSV file line by line.

Example: Reading a CSV File

using System;
using System.IO;

public class CsvReader
{
    public void ReadCsv(string filePath)
    {
        using (StreamReader 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()
    {
        CsvReader csvReader = new CsvReader();
        csvReader.ReadCsv("data.csv");
    }
}

Explanation:

  • Each line of the CSV file is read with ReadLine().
  • line.Split(‘,') splits each line into columns based on commas.
  • The columns are displayed 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

To handle files with empty lines or whitespace lines, you can use string.IsNullOrWhiteSpace() to skip these lines.

Example: Reading and Skipping Empty Lines

using System;
using System.IO;

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

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

Explanation:

  • The if (string.IsNullOrWhiteSpace(line)) continue; line checks if the line is empty or whitespace-only and skips it if true.

Sample content in sample_with_empty_lines.txt:

Line 1

Line 2


Line 3

Output:

Read line: Line 1
Read line: Line 2
Read line: Line 3

Summary

StreamReader in C# is a high-level class for reading text files efficiently and is ideal for applications that process text data.

Here’s a summary of the main points:

  • Basic Setup: StreamReader with using ensures that resources are managed properly.
  • Reading Line by Line: ReadLine() reads each line, making it efficient for large files.
  • Reading Entire File: ReadToEnd() loads the entire file content into a string, suitable for smaller files.
  • Reading Specific Parts: Read() allows you to read a specific number of characters using a buffer.
  • Different Encodings: Specify custom encodings like UTF-32 for files saved in non-standard encodings.
  • Structured Data (CSV): Parse structured files like CSV by reading line by line and splitting columns.

StreamReader is an essential tool for reading text files in C#, providing flexibility and efficiency for various text processing tasks.

You may also like