.NET Array Dictionary List String Sub ArrayList Cast Class Console Dates DataTable DateTime Enum File For Format If IndexOf Lambda LINQ Nothing Parse Process Property Regex Replace Select Sort Split StringBuilder SubstringStreamReader handles text files. We read a text file in VB.NET by Using StreamReader. This will correctly dispose of system resources and make code simpler. The best way to use StreamReader requires some special syntax.StreamWriter
Note:You need to add a text file called "file.txt" and include it in the build directory ("Copy if newer").
VB.NET program that uses StreamReader Imports System.IO Module Module1 Sub Main() ' Store the line in this String. Dim line As String ' Create new StreamReader instance with Using block. Using reader As StreamReader = New StreamReader("file.txt") ' Read one line from file line = reader.ReadLine End Using ' Write the line we read from "file.txt" Console.WriteLine(line) End Sub End Module Output (Contents of file.)
Also:We include the System.IO namespace at the top, with the line "Imports System.IO". This is important to compile the program.
VB.NET program that uses StreamReader and List Imports System.IO Module Module1 Sub Main() ' We need to read into this List. Dim list As New List(Of String) ' Open file.txt with the Using statement. Using r As StreamReader = New StreamReader("file.txt") ' Store contents in this String. Dim line As String ' Read first line. line = r.ReadLine ' Loop over each line in file, While list is Not Nothing. Do While (Not line Is Nothing) ' Add this line to list. list.Add(line) ' Display to console. Console.WriteLine(line) ' Read in the next line. line = r.ReadLine Loop End Using End Sub End Module
Also:There is a local line variable declared, which will store each line as it is read.List
And:I found that there were two string elements, containing Line 1 and Line 2 of the text file we read.
Finally:There are other methods on the File class that can simplify some of this code, but StreamReader proves to be an important tool.