Curriculum
In C#, the TextReader class is used to read characters from a stream in a sequential manner. It provides methods for reading strings, characters, and lines from a stream, as well as methods for checking the end of the stream and closing the stream.
Here is an example of using TextReader to read text from a file:
using System.IO; class Program { static void Main() { string filePath = "example.txt"; using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
In this example, we create a StreamReader object by specifying the file path. We then use the ReadLine method to read lines of text from the file, and we print each line to the console.
Here is an example of using TextReader to read text from the console:
using System; class Program { static void Main() { using (TextReader reader = Console.In) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
In this example, we create a TextReader object that reads from the console by using the Console.In property. We then use the ReadLine method to read lines of text from the console, and we print each line to the console.
Overall, TextReader is a useful class for reading text from streams in C#. It provides a high-level, convenient way to read text, but it does not provide the low-level control and efficiency of FileStream. It also requires careful attention to detail and proper error handling to ensure that streams are read correctly.