C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
OpenText: The TextReader is returned by File.OpenText. This is a common usage of TextReader.
FileReadLine: This method internally scans the file for the next newline sequence, and then consumes the text up to that point and returns it.
Environment.NewLineReadBlock: This method accepts a pre-allocated char[] array and the start index and count parameters. It fills the array elements before returning.
Char ArrayPeek: This method physically examines the file contents, and then returns the very next character that would be read.
C# program that uses TextReader class
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);
}
}
}
Output
First line
Fir
18
F
But: If you are trying to create your own reader object, using an instance field that is a TextReader is possibly preferable.
Review: The Peek method also allows you to preview what the TextReader will read next and where its reading position is.