物件 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
健全的程式設計
下列情況可能會導致拋出例外狀況:
路徑無效,原因如下:它是長度為零的字串、只包含空格符、包含無效字元,或是裝置路徑 (ArgumentException)。
路徑是無效的,因為它是
Nothing
(ArgumentNullException)。檔案不存在 (FileNotFoundException)。
檔案正由另一個進程使用,或發生 I/O 錯誤 (IOException)。
路徑超過系統定義的最大長度 (PathTooLongException)。
路徑中的檔案或目錄名稱包含冒號(:)或格式無效 (NotSupportedException)。
記憶體不足,無法將字串寫入緩衝區 (OutOfMemoryException)。
使用者缺少檢視路徑的必要許可權(SecurityException)。
請勿根據檔案名稱來判斷檔案內容。 例如,檔案 Form1.vb 可能不是 Visual Basic 來源檔案。
在應用程式中使用這些資料之前,請先驗證所有輸入值。 檔案的內容可能不是預期的內容,而且從檔案讀取的方法可能會失敗。