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 disposeor 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();
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *