Home
VB.NET
File.ReadLines Example
This page was last reviewed on Apr 2, 2022.
Dot Net Perls
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.
File
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.
IEnumerable
For
Here This program reads the data from a "file.txt" that is located in the same directory as the VB.NET executable.
And It displays that data to the screen with Console.WriteLine. Each String can be used in any way.
Console.WriteLine
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.
Array
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.
StreamReader
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 Apr 2, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.