The TextReader class in C# is a fundamental class that reads characters from a stream of text input. It is built into the System.IO namespace of C# and provides several methods and properties for reading character streams.
Example 1: Reading a Text File The following code example demonstrates how to use the TextReader class to read a text file and print its contents to the console.
using System; using System.IO;
class Program { static void Main(string[] args) { using (TextReader reader = File.OpenText("example.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
In this code example, we first open a text file called "example.txt" using the File.OpenText method. We then create a TextReader object from the opened file and use a while loop to read each line of the file using the ReadLine method. Finally, we print each line to the console using the Console.WriteLine method.
Example 2: Reading from a String The following code example demonstrates how to use the TextReader class to read from a string.
using System; using System.IO;
class Program { static void Main(string[] args) { string text = "example string"; using (TextReader reader = new StringReader(text)) { char[] buffer = new char[8]; int length = 0; while ((length = reader.Read(buffer, 0, buffer.Length)) != 0) { Console.Write(buffer, 0, length); } } } }
In this code example, we first define a string called "text". We then create a TextReader object from the string using the StringReader class. We use a while loop to read the string character by character using the Read method and store the characters in a character array called "buffer". Finally, we print the characters to the console using the Console.Write method.
The TextReader class is part of the .NET Framework Class Library, which is included in the .NET Standard Library and the .NET Core runtime.
C# (CSharp) TextReader - 60 examples found. These are the top rated real world C# (CSharp) examples of TextReader extracted from open source projects. You can rate examples to help us improve the quality of examples.