如何:在 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))
    
  • 对于大型二进制文件,可以使用 Read 对象的方法 FileStream 一次仅从文件中读取指定数量。 然后,您可以限制每次读取操作加载到内存中的文件数据量。 以下代码示例将复制文件,并允许调用方指定每次读取操作将文件读入内存的数量。

    ' 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 源文件。

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

另请参阅