如何:在 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
    

可靠编程

以下情况可能会导致引发异常:

不要根据文件的名称来判断文件的内容。 例如,Form1.vb 文件可能不是 Visual Basic 源文件。

在应用程序中使用输入的数据之前,需验证所有的输入内容。 文件的内容可能不是预期内容,并且用来读取该文件的方法可能失败。

请参见

任务

如何:在 Visual Basic 中读取具有多种格式的文本文件

参考

ReadAllBytes

WriteAllBytes

其他资源

从文件读取 (Visual Basic)

将数据存储到剪贴板以及从剪贴板读取数据 (Visual Basic)