Table of Contents
How Does TextReader Work in C#?
Examples of TextReader in C#
Example #4
Conclusion

TextReader in C#

Sep 03, 2024 pm 03:22 PM
c# c# tutorial

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);
Copy after login
Copy after login

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
}
Copy after login

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);
Copy after login
Copy after login

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.
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);
}
}
}
}
Copy after login

Output:

TextReader in C#

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);
}
}
}
}
Copy after login

Output:

TextReader in C#

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);
}
}
}
}
Copy after login

Output:

TextReader in C#

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);
}
}
}
}
Copy after login

Output:

TextReader in C#

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.

The above is the detailed content of TextReader in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

See all articles