The default with variables is that they only exist in RAM. Once your program is stopped, all your variables are removed from memory and you can not find their value again. How can one, in this case, record the best scores obtained at his game? How can you make a text editor if all the written text disappears when you stop the program?
Fortunately, you can read and write in C language files. These files will be written to your computer’s hard drive. The advantage is that they stay there, even if you stop the program or computer.
Now, we will use 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(); } } |
Alternative:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Program { static void Main(string[] args) { foreach (string line in File.ReadAllLines(@"D:\calisma\file.txt", Encoding.UTF8)) { Console.WriteLine(line); } Console.WriteLine("\nPress any key to exit."); Console.ReadKey(); } } |
Output: