TextReader ExamplesUse the TextReader class. TextReader is returned by File.OpenText.
This page was last reviewed on Apr 6, 2023.
TextReader reads text characters from a file. It is internally used by many other types in .NET. But you can access it for a general method of reading text content.
A warning. TextReader is used interally by StreamReader. But it is usually better to use StreamReader in your programs—StreamReader has more ease of use.
Example. Here we use the TextReader class. We use the using statement, providing for proper cleanup of the system resources related to the operating system and file system.
Info The TextReader is returned by File.OpenText. This is a common usage of TextReader.
Next The ReadLine method internally scans the file for the next newline sequence, and then consumes the text up to that point and returns it.
Detail ReadBlock() accepts a pre-allocated char array, start index and count parameters. It fills the array elements before returning.
Char Array
Finally Peek() examines the file contents, and then returns the very next character that would be read.
using System; using System.IO; class Program { static void Main() { // // Read one line with TextReader. // using (TextReader reader = File.OpenText(@"C:\perl.txt")) { string line = reader.ReadLine(); Console.WriteLine(line); } // // Read three text characters with TextReader. // using (TextReader reader = File.OpenText(@"C:\perl.txt")) { char[] block = new char[3]; reader.ReadBlock(block, 0, 3); Console.WriteLine(block); } // // Read entire text file with TextReader. // using (TextReader reader = File.OpenText(@"C:\perl.txt")) { string text = reader.ReadToEnd(); Console.WriteLine(text.Length); } // // Peek at first character in file with TextReader. // using (TextReader reader = File.OpenText(@"C:\perl.txt")) { char first = (char)reader.Peek(); Console.WriteLine(first); } } }
First line Fir 18 F
TextWriter. The TextWriter class is an abstract base class. StreamWriter implements additional logic for text encodings, making it a more useful class in many cases.
Info The StreamReader class contains additional logic for reading text files with various encodings more correctly.
But If you are trying to create your own reader object, using an instance field that is a TextReader is possibly preferable.
A summary. We explored the TextReader class. We can use the using statement with a resource acquisition statement, and then read lines, blocks of text, or entire files into strings.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 6, 2023 (edit).
© 2007-2023 Sam Allen.