VB.NET File.ReadLines Example

Use the File.ReadLines Function to read in each line of a text file and process it.

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 File.ReadLines, we read in a line at a time. This reduces memory usage.File

Example. File.ReadLines returns an IEnumerable(Of String). It reads in a line from the file, and then returns that string. We use it in a For-Each loop. When no more Strings are available, the loop terminates.For Each, 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.

File: file.txt This is a text line. This is a second line. VB.NET program that uses File.ReadLines 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 Output -- This is a text line. -- This is a second line.

Discussion. Choosing the best file-reading Function can be complicated. 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. 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.

String Array

Summary. File.ReadLines, added recently in the .NET Framework, loads each line of a file into a String. It does not process the entire file at once. Its effect can be duplicated with a StreamReader instance and its ReadLine Function.StreamReader
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to