방법: 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
    

강력한 프로그래밍

다음 조건에서는 예외가 throw될 수 있습니다.

  • 길이가 0인 문자열이거나, 공백만 포함하거나, 잘못된 문자를 포함하거나, 경로가 디바이스 경로인 경우와 같은 여러 가지 이유 중 하나로 경로가 올바르지 않은 경우(ArgumentException)

  • 경로가 Nothing이기 때문에 올바르지 않은 경우(ArgumentNullException)

  • 파일이 없는 경우(FileNotFoundException)

  • 다른 프로세스에서 파일을 사용 중이거나 I/O 오류가 발생한 경우(IOException)

  • 경로가 시스템 정의 최대 길이를 초과하는 경우(PathTooLongException)

  • 경로의 파일 이름이나 디렉터리 이름에 콜론(:)이 있거나 이름의 형식이 잘못된 경우(NotSupportedException)

  • 문자열을 버퍼에 쓰기 위한 메모리가 부족한 경우(OutOfMemoryException)

  • 경로를 보는 데 필요한 권한이 사용자에게 없는 경우(SecurityException)

파일 이름을 바탕으로 파일 내용을 판단하면 안 됩니다. 예를 들어 Form1.vb 파일이 Visual Basic 소스 파일이 아닐 수도 있습니다.

애플리케이션에서 데이터를 사용하기 전에 모든 입력을 확인해야 합니다. 파일의 내용이 예상한 내용과 다를 수 있으며 파일을 읽는 메서드가 실패할 수도 있습니다.

참고 항목