There are multiple ways to read a text file line by line. These include StreamReader.ReadLine, File.ReadLines, etc. Let's consider the text file that exists within our text file. The local computer has lines like below.
Using StreamReader.ReadLine -
C# StreamReader is used to read characters into the specified stream encoding. StreamReader.Read method reads the next character or next group of characters input stream. StreamReader inherits from TextReader and provides the following methods: Read a character, block, line or everything.
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(); } } }
Hi All!! Hello Everyone!! How are you?
File.ReadAllLines() method to open a text file and read all the lines of the file one
IEnumerable
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(); } } }
Hi All!! Hello Everyone!! How are you?
This is very similar to ReadLines. However, it returns String[] instead of
IEnumerable
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(); } } }
Hi All!! Hello Everyone!! How are you?
The above is the detailed content of What are the fastest ways to read a text file line by line using C#?. For more information, please follow other related articles on the PHP Chinese website!