How to use C# Textreader Class

TextReader and TextWriter are alternative options for reading and writing files in C#. Although they are not stream classes, they provide specialized functionality for handling character-based operations. The StreamReader and StreamWriter classes, derived from TextReader and TextWriter respectively, are specifically designed for reading characters from streams and writing characters to streams.

C# Textreader Class

To demonstrate the usage of TextReader for reading the entire content of a file into a string, you can refer to the following program:

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:\\net-informations.txt"); line = readFile.ReadToEnd(); MessageBox.Show(line); readFile.Close(); readFile = null; } catch (IOException ex) { MessageBox.Show(ex.ToString()); } } } }

When you execute this C# program , TextReader read the entire file in one stretch into a string.


Using TextReader in this manner, you can conveniently read and access the complete content of a file as a string, enabling further processing or manipulation as needed.