Lazily reading a file line-by-line via an IEnumerable

suggest change

When working with large files, you can use the System.IO.File.ReadLines method to read all lines from a file into an IEnumerable<string>. This is similar to System.IO.File.ReadAllLines, except that it doesn’t load the whole file into memory at once, making it more efficient when working with large files.

IEnumerable<string> AllLines = File.ReadLines("file_name.txt", Encoding.Default);

The second parameter of File.ReadLines is optional. You may use it when it is required to specify encoding.

Calling ToArray, ToList, or another buffering operator loads every line at once, which removes the benefit of ReadLines. Enumerate with foreach, or with a LINQ chain that you then enumerate once. foreach disposes the enumerator and closes the file. A leftover enumerator can keep the file open.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents