Dela via


How to: Read From Text Files in Visual Basic

The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The file encoding can be specified if the contents of the file use an encoding such as ASCII or UTF-8.

If you are reading from a file with extended characters, you will need to specify the file encoding.

To read from a text file

  • Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.txt into a string and then displays it in a message box.

    Dim fileReader As String
    fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
    MsgBox(fileReader)
    

To read from a text file that is encoded

  • Use the ReadAllText method of the My.Computer.FileSytem object to read the contents of a text file into a string, supplying the path and file encoding type. The following example reads the contents of the UTF32 file test.txt into a string and then displays it in a message box.

    Dim fileReader As String
    fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt", _
       System.Text.Encoding.UTF32)
    MsgBox(fileReader)
    

Robust Programming

The following conditions may cause an exception:

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also

Tasks

How to: Read From Comma-Delimited Text Files in Visual Basic

How to: Read From Fixed-width Text Files in Visual Basic

How to: Read From Text Files with Multiple Formats in Visual Basic

Troubleshooting: Reading from and Writing to Text Files

Walkthrough: Manipulating Files and Directories in Visual Basic

Concepts

File Encodings

Reference

My.Computer.FileSystem Object

My.Computer.FileSystem.ReadAllText Method

Other Resources

Reading from Files in Visual Basic