File.ReadLines. Large files present complications. If we read their entire contents into memory, we must store it all. This can make programs less efficient.
With ReadLines, we read in a line at a time. This reduces memory usage. For large files, File.ReadLines() is often a better choice—smaller files may be slower overall.
Example. ReadLines() returns an IEnumerable. It reads in a line from the file, and then returns that string. We use it in a For-Each loop—the loop ends when there are no more unread lines.
Imports System.IO
Module Module1
Sub Main()
' Loop over lines in file.
For Each line As String In File.ReadLines("file.txt")
' Display the line.
Console.WriteLine("-- {0}", line)
Next
End Sub
End Module-- This is a text line.
-- This is a second line.
Discussion. For small files, using a Function like File.ReadAllLines is sometimes faster. The memory cost of storing the entire file in memory at once is low.
Tip File.ReadAllLines stores the entire file contents in a String array. File.ReadLines does not.
However For large files, using a Function like File.ReadLines becomes superior. The memory pressure is reduced. Fewer garbage collections occur.
Important For small files, though, the overhead of the enumerator may be more expensive.
Also Some programs require a String array for further processing. In these cases, using ReadAllLines is better.
A summary. File.ReadLines() loads each line of a file into a String. It does not process the entire file at once. Its effect can be duplicated with StreamReader and its ReadLine Function.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 2, 2022 (edit link).