How to use C# Textreader Class

In addition to using stream classes, another approach to reading and writing files in C# involves utilizing the TextReader and TextWriter classes. These classes provide functionality specifically tailored for handling character-based operations.

C# Textreader Class

The TextReader class represents a reader capable of sequentially reading a series of characters. Derived from the TextReader class, the StreamReader class specializes in reading characters from streams and strings. On the other hand, the TextWriter class facilitates writing characters, while the StreamWriter class, derived from TextWriter, focuses on writing characters to streams and strings.

The following C# source code shows how to read a file using TextReader.

Full Source C#
using System; using System.Windows.Forms; using System.IO; using System.Text; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { string line = null; System.IO.TextReader readFile = new StreamReader("C:\\csharp.net-informations.txt"); while (true) { line = readFile.ReadLine(); if (line != null) { MessageBox.Show (line); } } readFile.Close(); readFile = null; } catch (IOException ex) { MessageBox.Show(ex.ToString()); } } } }

Conclusion

Using the TextReader and TextWriter classes, you can effectively manage file operations at a character level, offering more specific control over reading and writing textual content. These classes provide an alternative approach that complements the stream classes and adds flexibility to file manipulation tasks within the C# programming language.