TextReader and TextWriter in C#
Reading and writing text data in C#, the System.IO namespace provides abstract classes called TextReader and TextWriter. They offer a standard interface and a collection of techniques for reading and writing characters, strings, and lines of text from various sources.
TextReader:
The System.IO namespace contains an abstract class called TextReader. It serves as the fundamental class for character data reading from different sources. It offers a standard interface for reading text data, making it simple to work consistently with various input sources like files, streams, or strings.
- An abstract class called TextReader is used to read character data from a source. It offers ways to read individual characters, lines, and text blocks.
- Here are a few TextReader techniques that are frequently used:
Method | Description |
Read() | Retrieves the next character from the input source and returns the Unicode value of that character as an integer. If the input source's end is reached, it returns -1. |
Read(char[] buffer, int index, int count) reads | Reads a predetermined number of characters from the input source into the character array given and returns the number of characters read. |
ReadLine() | A line of characters is read from the input source and returned as a string by the function. If the input source's end is reached, the function returns null. |
Peek() | Without actually reading the character from the input source or stream, it returns the next character that is accessible. |
Close() | Exits the TextReader and releases all associated system resources. |
Dispose() | releases any resources held by the TextReader object and disposes of the object. Typically, when TextReader is used in a using statement, it is called automatically. |
ReadToEnd() | To read all characters from the current location to the end of the text reader, use the ReadToEnd() method. It returns all characters as a single string. This entails repeating a string including all characters from the present location to the text reader's finish. |
Synchronised() | Synchronized () wrap the provided TextReader in a thread-safe container. |
Example:
using System;
using System.IO;
class Program5
{
static void Main()
{
string filePath = @"D:\example.txt";
TextReader reader = null;
try
{
Reader = File.OpenText(filePath);
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
catch (FileNotFoundException)
{
Console.WriteLine(“File not found”);
}
catch (IOException)
{
Console.WriteLine(“An error occurred while reading the file.”);
}
finally
{
if (reader!= null)
reader.Close();
}
}
}
Output:
![TextReader and TextWriter in C#](https://static.tutorialandexample.com/csharp/text-reader-and-text-writer-in-csharp1.png)
Note: For these program to read correctly, please ensure that these file ”D:example.txt” exists and has some data. If not, you will receive the message “File not found”.
- A text file called "D:example.txt" contains the C# program that reads and displays the contents line by line.
- The correct error messages will be displayed if the File cannot be found or a reading problem occurs.
The "example.txt" File's contents, presuming the File is present and can be read, will be the program's output. The terminal will display each line of the File.
TextWriter in C#
The TextWriter class in C# is an abstract base class for writing character data to a stream. It is a component of the System.IO namespace. Writing text to a file, memory buffer, and another output destination can be replaced with an a higher-level abstraction.
- To the underlying output stream, this class offers methods for writing single characters, strings, and character arrays.
Methods | Description |
WriteLineAsync(string s) | This method encapsulates the supplied TextWriter in a thread-safe container. It ensures several threads can write to the same stream without encountering problems. |
Close() | the current writer and releasing any system resources it uses are accomplished via the Close() method. |
dispose() | The TextWriter object's resources are released by the method. After the writing is finished, it is advised to call Dispose or utilize the using statement to clear up resources appropriately. |
Flush() | Where all buffered data is to be written to the underlying device and clears all buffers for the current writer. |
Write(char ch) | Use this function to add one character at a time to the text stream. |
WriteAsync(char ch) | Use the function to add the character to the text stream asynchronously when you don't want the program to wait for the write operation to finish. |
Write(string s) | Use the Write(string s) function to add a string to the text stream. |
WriteLine() | A line terminator is added to the text stream using the WriteLine() function. Depending on the platform, it prints a new line character or a string of carriage return and line feed characters. |
WriteLineAsync(string s) | This function is used to write the string and a line terminator asynchronously. |
Example:
using System;
using System.IO;
class Program6
{
static void Main()
{
string filePath = "D:\examp.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write("welcome, ");
writer.WriteLine("Tutorials and example");
writer.WriteLine("Happy learning");
}
Console.WriteLine("Text written to the file");
}
Catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Output:
You should locate a file called "examp.txt" in the "D:" directory after this program has been compiled. Its contents are as follows:
![TextReader and TextWriter in C#](https://static.tutorialandexample.com/csharp/text-reader-and-text-writer-in-csharp2.png)
![TextReader and TextWriter in C#](https://static.tutorialandexample.com/csharp/text-reader-and-text-writer-in-csharp3.png)
C# program that uses the StreamWriter class is write text to a file. The program must write the provided text into a file called "examp.txt" in the "D:" directory.