• Reading and Writing to a Text File in Visual Basic

     Prerequisites

    • Import System.IO

    Reading a Text File

    Dim fs1 As New FileStream("TextFileIn.txt", FileMode.Open, FileAccess.Read)
    textFile1 as new StreamReader(fs1)
     
    Use textFile1.ReadLine to read the next line of text in the text file.
     
    Be sure to close the FileStream and StreamReader with:
    • fs1.Close()
    • textFile1.Close()

    Writing to a Text File

    Dim fs2 As New FileStream("TextFileOut.txt", FileMode.Append, FileAccess.Write)
    Dim textFile2 As New StreamWriter(fs2) 
     
    Use textFile2.WriteLine() to write the next line of text in the text file.
     
    Be sure to close the FileStream and StreamWriter with:
    • fs2.Close()
    • textFile2.Close()