共用方式為


如何:從 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 來源檔案。

在應用程式中使用這些資料之前,請先驗證所有輸入值。 檔案的內容可能不是預期的內容,而且從檔案讀取的方法可能會失敗。

另請參閱