Introduction to TextReader in C#
TextReader in C# is used to read text or sequential series of characters from a text file. TextReader class is found under System.IO namespace. It is an abstract base class of StreamReader and StringReader which are used to read characters from stream and string respectively. We cannot create an object of TextReader because it is an abstract class. TextReader is not threaded safe by default. Class deriving TextReader class needs to minimally implement Peek() and Read() methods in order to make a useful instance of TextReader.
Syntax:
Syntax of creating TextReader is as follows:
TextReader text_reader = File.OpenText(file_path);
The above statement will open a file at the location specified by ‘file_path’. Then, with the help of the text_reader, we can use the methods of TextReader class in order to read content from the file.
We can also create TextReader with the help of ‘using’ block as shown below:
using(TextReader text_reader = File.OpenText(file_path))
{
//user code
}
The advantage of working with ‘using’ block is that it releases the memory acquired by the object specified inside it after the work of the object is completed and the object is no longer required.
How Does TextReader Work in C#?
In order to work with TextReader, it is necessary to import System.IO namespace in our code. As TextReader is an abstract class, we cannot create its instance directly using ‘new’ keyword but we can use OpenText() method of the File class to achieve the same, as shown below:
TextReader text_reader = File.OpenText(file_path);
The OpenText() method takes the location of the file as input and then it opens an existing UTF-8 encoded text file at the same location for reading.
The File.OpenText() method returns an object of the StreamReader class which is the derived class of TextReader and thus helps in creating a useful instance of TextReader class in the code. This instance can be used to call the methods of TextReader class to read content from the file. TextReader class is derived from an abstract class MarshalByRefObject. Its inheritance hierarchy is shown below:
Object → MarshalByRefObject → TextReader
We can work with TextReader with the help of its two derived classes i.e. StreamReader and StringReader.
- StreamReader: It is used to read characters from a byte stream in a particular encoding.
- StringReader: It is used to read text from a string.
Please find some important methods of TextReader in the following table:
Method | Description |
Close() | It is used to close the TextReader and to release any system resources associated with it. |
Dispose() | It is used to release all the resources used by an object of TextReader. |
Peek() | It is used to read the next character without changing the state of the reader and it returns the next available character without actually reading it from the reader. |
Read() | It is used to read the next character from the text reader and it also advances the character position by one character. |
ReadLine() | It is used to read a line of characters from the text reader and it also returns the data as a string. |
ReadToEnd() | It is used to read all characters from the current position to the end of the text reader and it returns them as one string. |
Examples of TextReader in C#
We can pass a text file name in a TextReader constructor to create an object. Following are the different examples of TextReader in C#.
Example #1
Reading a line of a file using the ReadLine() method of TextReader.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
try
{
if (File.Exists(file))
{
// opening the text file and reading a line
using (TextReader textReader = File.OpenText(file))
{
Console.WriteLine(textReader.ReadLine());
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Output:
Example #2
Reading five characters from a file using the ReadBlock() method of TextReader.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
try
{
if (File.Exists(file))
{
//Opening the text file and reading 5 characters
using (TextReader textReader = File.OpenText(file))
{
char[] ch = new char[5];
textReader.ReadBlock(ch, 0, 5);
Console.WriteLine(ch);
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Output:
Example #3
Reading the whole content of a text file using the ReadToEnd() method of TextReader.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
string content = String.Empty;
try
{
if (File.Exists(file))
{
//Opening a text file and reading the whole content
using (TextReader tr = File.OpenText(file))
{
content = tr.ReadToEnd();
Console.WriteLine(content);
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Output:
Example #4
Reading the content of a text file using TextReader and writing it to another file.
Code:
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string fileToRead = @"E:\Content\TextReader.txt";
string fileToWrite = @"E:\Content\TextReaderAndWriter.txt";
StringBuilder content = new StringBuilder();
string str = String.Empty;
try
{
//checking if the file exists to read
if (File.Exists(fileToRead))
{
//Opening a text file and reading the whole content
using (TextReader textReader = File.OpenText(fileToRead))
{
while ((str = textReader.ReadLine()) != null)
{
content.Append("\n" + str);
}
}
}
else
{
Console.WriteLine("File does not exist!");
}
//checking if the file to write content already exists
if (File.Exists(fileToWrite))
{
File.Delete(fileToWrite);
}
//creating file if it does not exist
using (TextWriter textWriter = File.CreateText(fileToWrite))
{
textWriter.WriteLine(content);
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Output:
Conclusion
- TextReader is an abstract class that is used to read text or sequential series of characters from a text file.
- StreamReader and StringReader are two derived classes of TextReader with the help of which we can implement the methods of TextReader to read content from the text files.
Recommended Articles
This is a guide to TextReader in C#. Here we discuss the Introduction and how does TextReader works in C# along with examples and code implementation. You may also look at the following articles to learn more –