Reading from a Text File

In this lesson, you will learn how to read from a text file in Visual Basic by using the My.Computer.FileSystem Object.

The previous lesson, Writing to a Text File, describes how to add functionality to the Picture Viewer application that enables you to save the names of your favorite pictures to a text file. The next step is to read from the text file. This lets you view only your favorite pictures.

File Basics

Before you read from a text file, there are some things that you should know. The My object in Visual Basic makes working with files easy. You can read from files on a computer by using the My.Computer.FileSystem.ReadAllText Method of the My.Computer.FileSystem Object.

Text files that contain strings separated by commas are known as comma-delimited text files. Each item in the text file is known as a field. If you want to read the contents of a comma-delimited text file, you can use the My.Computer.FileSystem.OpenTextFieldParser Method.

In this procedure, you will check to make sure that the favorites text file exists in the Documents folder before you try to load it. The application will display a message to users if the file does not exist.

Note

In Windows XP, there are special folders named MyDocuments, MyPictures, and MyMusic. In Windows Vista, these folders do not have "My" in the names; instead, they are named Documents, Pictures, and Music. However, the code in this lesson will run on both Windows XP and Windows Vista.

Try It!

To read from a comma-delimited text file

  1. Open the Picture Viewer project from the previous lesson. If you have not yet completed it, go to Writing to a Text File and finish that lesson before you continue.

  2. In Solution Explorer, click Form1.vb, and then, on the View menu, click Designer.

  3. Add a Button control to the form, next to the Add to Favorites button.

  4. Change the following properties of this button:

    Property

    Value

    Name

    LoadFavorites

    Text

    Load Favorites

    Size

    85, 23

  5. Double-click the new Button control to add the default event handler in the Code Editor.

  6. In the LoadFavorites_Click event handler, add the following code to clear the contents of the list box and the picture box. If you don't first clear the list box, the file path and name will be appended to the list every time that you click the Load Favorites button.

    ' Clear the picture box and the list box.
    Me.ListBox1.Items.Clear()
    Me.PictureBox1.ImageLocation = ""
    
  7. Add the following If statement to check whether the FavoritePictures text file exists. If it doesn't, inform the user that the file does not exist.

    Dim FavoritePictures As String = 
     My.Computer.FileSystem.SpecialDirectories.MyDocuments &
       "\FavoritePictures.txt"
    If My.Computer.FileSystem.FileExists(FavoritePictures) Then
    
        ' Add code to read text from a file.
    
    Else
        MsgBox("There is no favorites file yet. Click Load" &
            " Pictures," & vbCrLf & "select a picture, and" &
            " then click Add to Favorites.", MsgBoxStyle.OkOnly, 
          "Picture Viewer")
    End If
    
  8. Replace the comment between the If statement and the Else statement with the following code. This code uses the OpenTextFieldParser method to read the contents of the FavoritePictures.txt file. It then indicates that the text delimiter is a comma.

    ' Open the FavoritePictures text file by using
    ' OpenTextFieldParser.
    Dim MyReader As Microsoft.VisualBasic.FileIO.TextFieldParser
    MyReader = My.Computer.FileSystem.OpenTextFieldParser( 
        FavoritePictures)
    MyReader.SetDelimiters(",")
    
  9. Add the following code underneath the code you added in the previous step. This code loops through the fields in the text file and then checks whether each file exists before adding it to the ListBox control. It then closes the TextFieldParser.

    ' Using a comma (,) as a delimeter, parse each field in 
    ' the text file and add it to the list box.
    Dim textFields As String() = MyReader.ReadFields()
    For Each currentField As String In textFields
       If My.Computer.FileSystem.FileExists(currentField) Then
            Me.ListBox1.Items.Add(currentField)
       End If
    Next
    
    ' Close the TextFieldParser.
    MyReader.Close()
    
  10. Press F5 to run the code.

  11. Click the Load Favorites button to load the files listed in the FavoritePictures.txt file.

  12. Click an item in the list box to view the picture in the Picture Viewer.

Next Steps

In this lesson, you learned how to read a comma-delimited text file and add each item in the file to a list. In the next lesson, you will learn how to delete the favorites text file from the Documents folder.

Next Lesson: Deleting a Text File

See Also

Tasks

Retrieving the Names of Files in a Folder

Writing to a Text File

Other Resources

Using the File System: Writing to and Reading from Files

Visual Basic Guided Tour