次の方法で共有


方法: 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
    

堅牢なプログラミング

次の条件を満たす場合は、例外がスローされる可能性があります。

  • パスは、長さ 0 の文字列、空白のみを含む、無効な文字が含まれている、またはデバイス パス (ArgumentException) のいずれかの理由で無効です。

  • パスは Nothing (ArgumentNullException) であるため無効です。

  • ファイルが存在しません (FileNotFoundException)。

  • ファイルが別のプロセスで使用されているか、I/O エラーが発生します (IOException)。

  • パスがシステム定義の最大長 (PathTooLongException) を超えています。

  • パス内のファイル名またはディレクトリ名にコロン (:)または無効な形式 (NotSupportedException) が含まれています。

  • バッファーに文字列を書き込むのに十分なメモリがありません (OutOfMemoryException)。

  • ユーザーには、パスを表示するために必要なアクセス許可がありません (SecurityException)。

ファイルの名前に基づいてファイルの内容を決定しないでください。 たとえば、Form1.vbファイルが Visual Basic ソース ファイルでない場合があります。

アプリケーションでデータを使用する前にすべての入力を確認します。 ファイルの内容が想定どおりでない可能性があり、ファイルから読み取るメソッドが失敗する可能性があります。

こちらも参照ください