C# Textreader

In C# programming, the TextReader class belongs to the System.IO namespace and serves as a means to access and read text or a series of characters sequentially. This fundamental class is a component of .NET and serves as the foundation for StreamReader and StringReader classes. The StreamReader in C# is frequently employed for reading characters from a stream, while the StringReader is typically used for reading characters from a string. Nevertheless, both classes can be employed for text reading purposes.

The styling for the placeholder includes a background with a linear gradient, rounded corners, padding, and center alignment. Inside, there is an icon and text styled with specific colors and sizes.

Syntax:

It has the following syntax.

Example

TextReader reader = new DerivedTextReader ();

In this syntax,

  • TextReader: It is used to represent an abstract base class in the System.IO namespace.
  • reader: It is the variable name that will hold the reference to the TextReader Object.
  • new: It is the keyword that creates an instance of the derived class.
  • DerivedTextReader: It represents the constructor of a class that derives from TextReader.
  • Simple C# TextReader Example

Let's consider a scenario to demonstrate the functionality of the TextReader in C#.

Example

Example

using System;  

using System.IO;  

namespace TextReaderExample  

{  

    class C# Tutorial  

    {  

        static void Main(string[] args)  

        {  

            using (TextReader tr = File.OpenText("e:\\f.txt"))  

            {

                Console.WriteLine(tr.ReadToEnd());  

            }  

        }  

    }  

}

Output:

Output

Hello C#

C# File Handling by C# Tutorial.

Explanation:

In this instance, we are employing the TextReader class in C#. Initially, we utilize the File.OpenText technique to access a text file named f.txt situated at the designated path (f.txt). Subsequently, we employ the ReadToEnd function to retrieve all the file content and exhibit the result through the Console.WriteLine operation.

C# TextReader Example to Read One Line

Let's consider an instance to demonstrate the TextReader class for reading a solitary line from the file.

Example

Example

using System;

using System.IO;

namespace C# Tutorial

{  

    class Program  

    {  

        static void Main(string[] args)  

        {  

            using (TextReader tr = File.OpenText("e:\\f.txt"))  

            {  

                Console.WriteLine(tr.ReadLine());  

            }  

        }  

    }  

}

Output:

Output

Hello C#

Explanation:

In this instance, we employ the File.OpenText function to access the f.txt file. The specified path for the file is e:\\f.txt. Within the using block, the ReadLine function is utilized to retrieve the initial line of the file's content. Finally, the output is displayed using the Console.WriteLine function.

How to read a file using StreamReader in C#

In C#, the StreamReader class is frequently utilized for reading text files, offering a functionality to retrieve data from files sequentially, one line at a time. This streamlines the process of managing files, making it easier and more user-friendly.

Here, we will explore the process of sequentially accessing and retrieving data from a file in C#.

1) Create an Object of FileInfo

To instantiate an object of the FileInfo class, we can utilize the syntax below:

Example

FileInfo file = new FileInfo(@" D:C# Tutorialfile.txt " );

In this particular format, the FileInfo class is employed to retrieve details about a file and execute actions such as creating, opening, deleting, or relocating files. A FileInfo object is instantiated for the specified location D:C# Tutorialfile.txt.

2) Open the File for Reading

We can utilize the following statement to open the file for reading.

Example

FileStream fs = file.Open(FileMode.OpenOrCreate, FileAccess.Read , FileShare.Read);

In this syntax,

  • FileStream: The FileStream is a class in the System.IO namespace. It is utilized to read or write files.
  • fs: The fs is the object of type Filestream that will store the reference to the opened file stream.
  • Open : The Open method of FileInfo is utilized to open an existing file or create a new file.
  • OpenOrCreate: It is the parameter that defines how we can open or create a file.
  • 3) Create a Stream Reader Object

To instantiate a stream reader object, we can utilize the syntax below:

Example

StreamReader sr = new StreamReader ( fs );

In this syntax,

  • StreamReader: It is the class that is used to read characters or text.
  • sr: It is an object of the StreamReader class.
  • new: It is the keyword that creates an instance of the StreamReader class.
  • fs: It is an argument that is passed to the StreamReader.
  • 4) Read All Content from the File

If there is a need to access and read the entire content of a file, we can make use of the following syntax:

Example

string fileContent = sr.ReadToEnd();

In this particular syntax,

  • fileContent refers to a string variable designated to hold the information retrieved from the file.
  • 5) Close the StreamReader and FileStream

To properly close the StreamReader and FileStream, the following syntax can be utilized:

Example

sr.Close();

fs.Close();

In this particular structure,

  • Shutdown: The sr.Shutdown function is employed to terminate the StreamReader instance.
  • Shutdown: The fs.Shutdown function is utilized to conclude the FileStream instance.
  • C# TextReader Methods

There are numerous frequently employed techniques for TextReader in C#. A selection of these includes:

Methods Description
Close() The Close() method is commonly utilized to close the TextReader and release any resources associated with it.
Dispose() The Dispose() method is used to clean up and releasing the resources utilized by the TextReader object.
Dispose (Boolean) The Dispose (Boolean) method is used to free the unmanaged resources utilized by the TextReader, and it can also release the managed resources.
Equals(Object) The Equals (Object) method checks whether the current object and the given object have the same value.
GetType() It retrieves the type information of the current object.
Read() The Read() method is commonly utilized to read the next character from the input stream.
Peek() The Peek() method reads the next character from the text reader without changing the current position.
Read(Span_PRESERVE15__) This method is commonly used to read a sequence of characters from the current text reader and writes them into the specified character span.
ReadBlockAsync(Char[], int32, int32) It performs an asynchronous operation to read a certain number of characters from the text reader.
ReadAsync(Memory_PRESERVE16__, CancellationToken) It is commonly utilized to read the characters from the current stream into a memory block.
ReadLine() The ReadLine() method is commonly utilized to read one line of text from the text reader. It returns the data in a string format.
ReadLineAsync(Cancellation Token) It is commonly utilized to read characters asynchronously from the existing position to the end of the text reader, and it returns in a string format.
ReadLineAsync() This method is used to read characters asynchronously, and it returns the data in a string format.
ReadToEnd() This method reads all remaining characters from the current position to the end of the text reader, and it returns the data in a string format.
ReadToEndAsync() The ReadToEndAsync() method reads all the characters from the existing position to the end of the text reader asynchronously, and it returns the data in a string format.
ToString () This method is commonly utilized to return a string that shows the current object.
Synchronized (TextReader) It provides a synchronized wrapper for the given TextReader to ensure thread safety.
ReadToEndAsync (Cancellation Token) This method reads all the characters asynchronously from the existing position to the end of the text reader, and it returns in a string format.
GetLifetimeService () This method is used to retrieve the object that handles the lifetime of the instance.
MemberwiseClone () This method is commonly utilized to create a shallow copy of the current object.

C# TextReader Example with different Methods

Let's consider an example to demonstrate the various techniques of utilizing TextReader in C#.

Example

Example

using System;

using System.IO;

class Tpt

{

    static void Main()

    {

        // file exists at the specified path

        string filePath = @" E:\sample.txt ";

        // Using TextReader 

        using (TextReader reader = new StreamReader( filePath) )

        {

            // Read the first line

            string line = reader.ReadLine();

            Console.WriteLine(" The First Line: " + line);

            // Peek at the next character 

            int nextChar = reader.Peek();

            Console.WriteLine("Next Character ASCII Code: " + nextChar );

            // Read the rest of the file

            string remainingText = reader.ReadToEnd ();

            Console.WriteLine(" Remaining Text:\n" + remainingText );

        }

    }

}

Output:

Output

The First Line: Hello C#

Next Character ASCII Code: 10

Remaining Text:

This is a TextReader example.

Enjoy learning!

Explanation:

In this instance, we instantiate the TextReader instance to access the text stored in a file at E:\sample.txt. Following this, the ReadLine function retrieves the initial line from the file. Subsequently, we employ the Peek function to inspect the upcoming character in the file. Utilizing the ReadToEnd function allows us to extract all characters from the present location. Lastly, we utilize the Console.WriteLine function to display the result.

Features of the TextReader Class in C#

There are several features of the TextReader Class in C#. Some of them are as follows:

  • In the C# programming language, the TextReader class is an abstract class that can provide a platform for reading-based data from text files or streams.
  • It can provide several asynchronous methods, such as ReadAsync, ReadLineAsync, and ReadToEndAsync methods that allow us to perform non-blocking I/O operations.
  • We can use the TextReader class with several input resources, including files or strings, which makes it versatile and flexible for several text-reading operations.
  • We can utilize the TextReader class to read the sequential streams of characters, which makes it suitable to handle text input instead of binary data.
  • It can be defined under the System.IO namespace.
  • Conclusion

In summary, a TextReader serves as a fundamental class in the C# programming language. Its primary function involves extracting characters from sources of text such as files or strings. This class offers a range of functions like Read, ReadLine, ReadToEnd, and Peek among others. These functions enable users to securely and conveniently retrieve code from various origins. Furthermore, TextReader facilitates the efficient, secure, and adaptable extraction of text from diverse sources.

C# TextReader FAQs

1) What is the TextReader class in C#?

In C# programming, the TextReader class exists within the System.IO namespace. This class serves as a means to access and read text or a sequence of characters in a sequential manner. TextReader is a fundamental component of .NET and acts as a superclass for both the StreamReader and StringReader classes.

2) What is the syntax of TextReader in C#?

It has the following syntax.

Example

TextReader reader = new DerivedTextReader();

In this syntax,

  • TextReader: It is an abstract base class in the System.IO namespace.
  • reader: It is the variable name that will hold the reference to the TextReader Object.
  • new: It is the keyword that creates an instance of the derived class.

3) What are some of the classes that inherit from TextReader in C#?

In C#, the StreamReader and StringReader classes inherit from the TextReader class.

4) How do we read a line from a text in C#?

In C#, the ReadLine function of a TextReader is frequently used to retrieve a single line of text content. This method is commonly employed to extract a line of characters from the text reader and presents the information as a string.

5) What is the Peek method in C#?

The Peek function is primarily utilized to retrieve the upcoming character from the text reader without altering the current position. It provides the subsequent character in the form of an integer, or -1 if there are no more characters accessible.

Input Required

This code uses input(). Please provide values below: