File.ReadLines() method to read a text file that has lots of lines. File.ReadLines() method internally creates Enumerator. So we can call it in the foreach and every time foreach asks for a next value, it calls StreamReader.ReadLine under the hood.
C# Code: You can use File.ReadLines and foreach to read whole file line by line
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Program { static void Main(string[] args) { // Read each line of the file into a string array. Each element // of the array is one line of the file. string[] lines =File.ReadAllLines(@"D:\sample\file.txt"); // Display the file contents by using a foreach loop. Console.WriteLine("Contents of file.txt = "); foreach (string line in lines) { // Use a tab to indent each line of the file. Console.WriteLine("\t" + line); } // Keep the console window open in debug mode. Console.WriteLine("\nPress any key to exit."); Console.ReadKey(); } } |