c-sharp
  1. c-sharp-textreader

C# TextReader

In C#, the TextReader class is used to read characters from a text stream in a specific encoding. It provides convenient methods for reading and buffering text from a file or input stream. In this tutorial, we'll discuss how to use the TextReader class in C#.

Syntax

The syntax for using the TextReader class in C# is as follows:

TextReader reader = new StreamReader("filename.txt");
string line = reader.ReadLine();

In this example, we create a new instance of the TextReader class by calling the StreamReader constructor with the filename of the text file we want to read. We then read a single line from the text file using the ReadLine method.

Example

Let's say we have a text file called "input.txt" that contains the following text:

Hello
World

We can read this text file using the TextReader class in C#:

using System;
using System.IO;

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

Output

When we run the example code above, the output will be:

Hello
World

This is because we read each line of the "input.txt" file using the TextReader class and printed it to the console.

Explanation

In the example above, we used the TextReader class to read a text file called "input.txt". We created a new instance of the TextReader class by calling the StreamReader constructor with the name of the file we want to read. We then used the ReadLine method to read each line of the file and printed it to the console using Console.WriteLine. Finally, we closed the TextReader object to release any system resources.

Use

The TextReader class is useful for reading text data from files, strings, or other input streams. You can use it to read and buffer text data, which can be useful for processing large amounts of text data or parsing structured text streams.

Important Points

  • The TextReader class provides convenient methods for reading and buffering text data from input streams.
  • It is important to close the TextReader object when you are done with it to release any system resources it is using.
  • The TextReader class is part of the System.IO namespace.

Summary

In this tutorial, we discussed how to use the TextReader class in C# to read text data from files or input streams. We covered the syntax, example, output, explanation, use, and important points of the TextReader class. With this knowledge, you can now use the TextReader class in your C# code to read and process text data.

Published on: