Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are some of the fastest way to read a text file line by line using C#?
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?