如何:使用 StreamReader 读取文件中的文本 (Visual Basic)How to: Read Text from Files with a StreamReader (Visual Basic)

My.Computer.FileSystem 对象提供打开 TextReaderTextWriter 的方法。The My.Computer.FileSystem object provides methods to open a TextReader and a TextWriter. 这些方法(OpenTextFileWriterOpenTextFileReader)是高级方法,除非选择“全部” 选项卡,否则它们不会出现在 IntelliSense 中。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

  • 使用 OpenTextFileReader 方法打开 TextReader 并指定文件。Use the OpenTextFileReader method to open the TextReader, specifying the file. 此示例打开名为 testfile.txt 的文件、从中读取一行,然后在消息框中显示该行。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. 例如,文件 Form1.vb 可能不是 Visual Basic 源文件。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.

.NET Framework 安全性.NET Framework Security

若要从文件中读取,程序集需要 FileIOPermission 类授予的特权等级。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. 有关详细信息,请参阅 ACL 技术概述For more information, see ACL Technology Overview.

另请参阅See also