如何:在 Visual Basic 中读取二进制文件
My.Computer.FileSystem 对象提供了用于读取二进制文件的 ReadAllBytes 方法。
读取二进制文件
使用 ReadAllBytes 方法,以字节数组的形式返回文件的内容。 此示例读取文件 C:/Documents and Settings/selfportrait.jpg。
Dim bytes = My.Computer.FileSystem.ReadAllBytes( "C:/Documents and Settings/selfportrait.jpg") PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))
对于大型二进制文件,可以使用 FileStream 对象的 Read 方法,一次仅从文件读取指定的量。 然后,可以限制每个读取操作将文件中的多少数据加载到内存中。 下面的代码示例复制文件,并允许调用方指定每个读取操作将文件中的多少数据读取到内存中。
' This method does not trap for exceptions. If an exception is ' encountered opening the file to be copied or writing to the ' destination location, then the exception will be thrown to ' the requestor. Public Sub CopyBinaryFile(ByVal path As String, ByVal copyPath As String, ByVal bufferSize As Integer, ByVal overwrite As Boolean) Dim inputFile = IO.File.Open(path, IO.FileMode.Open) If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then My.Computer.FileSystem.DeleteFile(copyPath) End If ' Adjust array length for VB array declaration. Dim bytes = New Byte(bufferSize - 1) {} While inputFile.Read(bytes, 0, bufferSize) > 0 My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True) End While inputFile.Close() End Sub
可靠编程
以下情况可能会导致引发异常:
路径由于以下原因之一而无效:它是零长度字符串;它仅包含空白;它包含无效字符;或者它是一个设备路径 (ArgumentException)。
路径无效,因为它是 Nothing (ArgumentNullException)。
该文件不存在 (FileNotFoundException)。
文件正由另一个进程使用,或者出现 I/O 错误 (IOException)。
路径超过了系统定义的最大长度 (PathTooLongException)。
路径中的文件名或目录名包含冒号 (:),或格式无效 (NotSupportedException)。
内存不足,无法将字符串写入缓冲区 (OutOfMemoryException)。
该用户缺少查看该路径所必需的权限 (SecurityException)。
不要根据文件的名称来判断文件的内容。 例如,Form1.vb 文件可能不是 Visual Basic 源文件。
在应用程序中使用输入的数据之前,需验证所有的输入内容。 文件的内容可能不是预期内容,并且用来读取该文件的方法可能失败。
请参见
任务
如何:在 Visual Basic 中读取具有多种格式的文本文件