Open a text file and read line by line in C#
There are several ways to open a text file and read line by line in c# programming language. The most common method is to use StreamReader to read a file line by line.
Reading From File Line by Line with StreamReader in C#
using (StreamReader sr = File.OpenText("path"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
It is also possible to use TextReader to read a file line by line in C#.
TextReader tr = new StreamReader("path");
Console.WriteLine(tr.ReadLine());
tr.Close();
Reading a text file into String[] in C#
Another method for reading a text file line by line is to use File.ReadAllLines method. If your file is small enough or if you want to access these lines multiple times, then you might load all the lines into memory and re-use them as given below:
string[] lines = File.ReadAllLines("path");
foreach (string line in lines)
{
if (line.Length > 80)
{
Console.WriteLine(line);
}
}