TextReader
TextReader is an abstract class in the System.IO namespace that provides a generic way to read characters from a stream. It defines a set of methods for reading different types of data from a stream, such as text, arrays, and objects.
TextReader is the base class for a number of more specific reader classes, such as StreamReader and StringReader. These classes provide additional functionality for reading data from specific types of streams, such as files or strings.
Here are some of the most commonly used methods of TextReader:
Read: Reads a single character from the input stream.
ReadBlock: Reads a specified number of characters from the input stream into a buffer.
ReadLine: Reads a line of characters from the input stream.
ReadToEnd: Reads all characters from the current position to the end of the input stream.
Here's an example that demonstrates how to use TextReader to read text from a file:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.txt";
using (TextReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
In this example, we create a new StreamReader object that reads from the file at the specified path. We then use a while loop to read each line of text from the file using the ReadLine method, and print it to the console. The using statement ensures that the reader is properly disposed of when we're finished with it.
Comments
Post a Comment