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.
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.
Console.WriteLine
. Each String
can be used in any way.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.
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.
File.ReadAllLines
stores the entire file contents in a String
array. File.ReadLines
does not.File.ReadLines
becomes superior. The memory pressure is reduced. Fewer garbage collections occur.String
array for further processing. In these cases, using ReadAllLines
is better.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.