File.ReadLines Example
This page was last reviewed on May 26, 2021.
Dot Net Perls
File.ReadLines. This C# method reads lines on demand. We use it in a foreach-loop, looping over each line as a string. It can result in clean, simple code.
Method details. How does File.ReadLines work? The program reads in another line before each iteration of the foreach-loop. It loads the file on-demand.
Example code. This program calls the File.ReadLines method in the foreach loop iteration block. The File.ReadLines method is only called once.
Info The IEnumerable is used to pull in more data. The program successfully prints the data found in the "file.txt" file.
Important With File.ReadLines, the foreach-loop is the best syntax as it avoids copying the IEnumerable to another collection in memory.
using System; using System.IO; class Program { static void Main() { // Read in lines from file. foreach (string line in File.ReadLines("c:\\file.txt")) { Console.WriteLine("-- {0}", line); } } }
-- Line1 -- Line2 -- Line3 -- Another line. -- Last line.
ReadAllLines. ReadLines and ReadAllLines are implemented differently. ReadLines uses an enumerator to read each line only as needed.
And On the other hand, ReadAllLines reads the entire file into memory and then returns an array of those lines.
Info If the file is large, the File.ReadLines method is useful because it will not need to keep all the data in memory at once.
Also If your program exits the loop early, the File.ReadLines is better because no further IO will be needed.
Thus The File.ReadAllLines method is best if you need the entire array. The array can be stored in a field in a class.
Summary. The File.ReadLines method is similar to using the StreamReader type and the ReadLine method in a loop. You can use a foreach-loop to read in an entire file line-by-line.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 26, 2021 (rewrite).
© 2007-2024 Sam Allen.