What are some of the fastest way to read a text file line by line using C#?

CsharpServer Side ProgrammingProgramming

There are several ways to read a text file line by line. Those includes StreamReader.ReadLine, File.ReadLines etc. Let us consider a text file present in our local machine having lines like below.

Using StreamReader.ReadLine −

C# StreamReader is used to read characters to a stream in a specified encoding. StreamReader.Read method reads the next character or next set of characters from the input stream. StreamReader is inherited from TextReader that provides methods to read a character, block, line, or all content.

Example

using System;
using System.IO;
using System.Text;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         using (var fileStream = File.OpenRead(@"D:\Demo\Demo.txt"))
         using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)){
            String line;
            while ((line = streamReader.ReadLine()) != null){
               Console.WriteLine(line);
            }
         }
         Console.ReadLine();
      }
   }
}

Output

Hi All!!
Hello Everyone!!
How are you?

Using File.ReadLines

The File.ReadAllLines() method opens a text file, reads all lines of the file into a IEnumerable<string>, and then closes the file.

Example

using System;
using System.IO;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         var lines = File.ReadLines(@"D:\Demo\Demo.txt");
         foreach (var line in lines){
            Console.WriteLine(line);
         }
         Console.ReadLine();
      }
   }
}

Output

Hi All!!
Hello Everyone!!
How are you?

Using File.ReadAllLines

This is very much similar to ReadLines. However, it returns String[] and not an IEnumerable<String> allowing us to randomly access the lines.

Example

using System;
using System.IO;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         var lines = File.ReadAllLines(@"D:\Demo\Demo.txt");
         for (var i = 0; i < lines.Length; i += 1){
            var line = lines[i];
            Console.WriteLine(line);
         }
         Console.ReadLine();
      }
   }
}

Output

Hi All!!
Hello Everyone!!
How are you?
raja
Published on 24-Sep-2020 15:57:51
Advertisements