C# TextReader

In c#, TextReader is a class of System.IO namespace, and it is useful to read a text or sequential series of characters in the file.

 

Now, we will see how to use the TextReader class in c# to read a text or sequential series of characters in the file with examples.

C# TextReader Example

Following is the example of reading a text or sequential series of characters in a file using the TextReader object in c#.

 

using System;
using System.IO;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          string fpath = @"D:\Test.txt";
          // Check if file exists
          if (File.Exists(fpath))
          {
             // Open the file and read
             using (TextReader tr = File.OpenText(fpath))
             {
                 Console.WriteLine(tr.ReadToEnd());
             }
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we imported a System.IO namespace to access File & TextReader objects to open and read text from the given file.

 

When we execute the above example, it will read the text from “Test.txt” file in D drive and return the result as shown below.

 

C# TextReader to Read Text from File Example Result

 

If we want to read only the first line of characters from the file, we need to modify the text reading code, as shown below.

 

// Open the file and read
using (TextReader tr = File.OpenText(fpath))
{
   Console.WriteLine(tr.ReadLine());
}

This is how we can use TextReader class in c# to read data from the file in file system.