EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

TextReader in C#

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » TextReader in C#

TextReader in C#

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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.

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

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:

TextReader in C# 1-1

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:

TextReader in C# 1-2

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:

TextReader in C# 1-3

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:

TextReader in C# 1-4

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 –

  1. Abstract Class in C#
  2. C# Abstract vs Interface
  3. Static Constructor in C#
  4. C# Dynamic

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More