Share via


How to: Read Text from Files with a StreamReader (Visual Basic)

The My.Computer.FileSystem object provides methods to open a TextReader and a TextWriter. These methods, OpenTextFileWriter and OpenTextFileReader, are advanced methods that do not appear in IntelliSense unless you select the All tab.

To read a line from a file with a text reader

  • Use the OpenTextFileReader method to open the TextReader, specifying the file. This example opens the file named testfile.txt, reads a line from it, and displays the line in a message box.

    Dim fileReader As System.IO.StreamReader
    fileReader = _
    My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
    Dim stringReader As String
    stringReader = fileReader.ReadLine()
    MsgBox("The first line of the file is " & stringReader)
    

Robust Programming

The file that is read must be a text file.

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.

Security

To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see Code Access Security Basics. The user also needs access to the file. For more information, see Access Control Lists (ACLs).

See Also

Reference

My.Computer.FileSystem Object

OpenFileDialog

My.Computer.FileSystem.OpenTextFileWriter Method

My.Computer.FileSystem.OpenTextFileReader Method

Other Resources

SaveFileDialog Component (Windows Forms)

Reading from Files in Visual Basic