C# TextReader Class with Programming Example

In this chapter you will learn:
  • What is TextReader Class and How it Works?
  • Methods of TextReader Class
  • Easy Programming Examples

What is TextReader Class?

TextReader Class represents a reader that can read a sequential series of Characters. It is abstract class that means you cannot instantiate it. After finishing reading or writing file you must dispose or clean memory directly or indirectly. To directly dispose, call Dispose Method in try/catch block and for indirectly disposal write code inside using block.

Programming Examples:

In this programming Example I will open D:\csharpfile.txt using TextReader class, read file and print output on console.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TextReader_class
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"D:\csharpfile.txt";

            //Read One Line
            using(TextReader tr=File.OpenText(filepath))
            {   
                Console.WriteLine(tr.ReadLine());
            }

            //Read 4 Characters
            using (TextReader tr = File.OpenText(filepath))
            {   
                char[] ch = new char[4];
                tr.ReadBlock(ch, 0, 4);
                Console.WriteLine(ch);
            }

            //Read full file
            using (TextReader tr = File.OpenText(filepath))
            {
                Console.WriteLine(tr.ReadToEnd());
            }
            Console.ReadKey();
        }
    }
}

Output
Hello File Handling!
Hell
Hello File Handling!
_

Summary

In this chapter you learned TextReader class using complete programming example. In the next chapter you will learn BinaryWriter Class in C#.

 

Share your thought