TextReader in C#
TextReader class available in .NET is a base class for StreamReader
and StringReader classes. The StreamReader is used to read characters from a
stream. The StringReader is used to read characters from a string. You must use
either a StreamReader or a StringReader to read text. These classes are defined
in the System.IO namespace. You must import the System.IO namespace before you
can use these classes.
Creating a TextReader
We can pass a text file name in a StreamReader constructor to
create an object.
Here is C# code. Make sure you have correct path of your text
file.
StreamReader sr = new
StreamReader(@"C:\Mahesh\King.txt");
Here is VB.NET code:
Dim sr As New StreamReader("C:\Mahesh\King.txt")
Read Methods
The Read method reads the next character from the input stream and
advances the character position by one character. The overloaded Read method
also takes two parameters, a starting index and number of characters.
The ReadLine method reads a line of characters from the current
stream and returns the data as a string.
The ReadBlock method reads a maximum of count characters from the
current stream, and writes the data to buffer, beginning at index.
The ReadToEnd method
reads all characters from the current position to the end of the TextReader and
returns them as one string.
The Peek method reads the next character without changing the
state of the reader or the character source. As the name says peek, it actually
peeks and returns the next available character without actually reading it from
the input stream.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace TextReaderSample
{
class Program
{
static void Main(string[] args)
{
using (StreamReader
sr = new StreamReader(@"C:\Mahesh\King.txt"))
{
String line;
// Read line by line
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
Here is VB.NET code:
Imports System.IO
Module Module1
Sub Main()
Using sr As New StreamReader("C:\Mahesh\King.txt")|
Dim line As String
Do
line = sr.ReadLine()
If Not
(line Is Nothing)
Then
Console.WriteLine(line)
End If
Loop Until line Is Nothing
End Using
Console.ReadKey()
End Sub
End Module
Summary
In this article, we discussed how to read a text file using a
StreamReader.
Here are some more articles:
Text Reader and
Text Writer in C#
StreamReader and
StreamWriter Classes in C#