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
강력한 프로그래밍
다음 조건으로 인해 예외가 발생할 수 있습니다.
경로는 길이가 0인 문자열이거나, 공백만 포함하거나, 잘못된 문자를 포함하거나, 디바이스 경로(ArgumentException)인 등의 이유로 유효하지 않습니다.
경로가 (
Nothing
)이므로 ArgumentNullException 유효하지 않습니다.파일이 없습니다(FileNotFoundException).
파일이 다른 프로세스에서 사용 중이거나 I/O 오류가 발생합니다(IOException).
경로가 시스템 정의 최대 길이(PathTooLongException)를 초과합니다.
경로의 파일 또는 디렉터리 이름에 콜론(:) 포함되거나 잘못된 형식(NotSupportedException)이 있습니다.
버퍼(OutOfMemoryException)에 문자열을 쓸 메모리가 부족합니다.
사용자에게 경로(SecurityException)를 보는 데 필요한 권한이 없습니다.
파일 이름을 바탕으로 파일 내용을 판단하면 안 됩니다. 예를 들어 Form1.vb 파일이 Visual Basic 소스 파일이 아닐 수도 있습니다.
애플리케이션에서 데이터를 사용하기 전에 모든 입력을 확인해야 합니다. 파일의 내용이 예상과 다를 수 있으며 파일에서 읽는 메서드가 실패할 수 있습니다.
참고하십시오
.NET