이 예제에서는 파일 크기와 관련된 5개의 쿼리(바이트)를 보여 줍니다.
가장 큰 파일의 크기(바이트)를 검색하는 방법입니다.
가장 작은 파일의 크기(바이트)를 검색하는 방법입니다.
지정된 루트 폴더 아래 FileInfo 의 하나 이상의 폴더에서 가장 크거나 작은 개체 파일을 검색하는 방법입니다.
가장 큰 10개 파일과 같은 시퀀스를 검색하는 방법입니다.
지정된 크기보다 작은 파일을 무시하고 파일 크기를 바이트 단위로 기준으로 파일을 그룹으로 정렬하는 방법입니다.
예시
다음 예제에는 파일 크기(바이트)에 따라 파일을 쿼리하고 그룹화하는 방법을 보여 주는 5개의 개별 쿼리가 포함되어 있습니다. 이러한 예제를 쉽게 수정하여 개체의 다른 속성에 대한 쿼리를 FileInfo 기반으로 할 수 있습니다.
Module QueryBySize
Sub Main()
' Change the drive\path if necessary
Dim root As String = "C:\Program Files\Microsoft Visual Studio 9.0"
'Take a snapshot of the folder contents
Dim dir As New System.IO.DirectoryInfo(root)
Dim fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories)
' Return the size of the largest file
Dim maxSize = Aggregate aFile In fileList Into Max(GetFileLength(aFile))
'Dim maxSize = fileLengths.Max
Console.WriteLine("The length of the largest file under {0} is {1}", _
root, maxSize)
' Return the FileInfo object of the largest file
' by sorting and selecting from the beginning of the list
Dim filesByLengDesc = From file In fileList _
Let filelength = GetFileLength(file) _
Where filelength > 0 _
Order By filelength Descending _
Select file
Dim longestFile = filesByLengDesc.First
Console.WriteLine("The largest file under {0} is {1} with a length of {2} bytes", _
root, longestFile.FullName, longestFile.Length)
Dim smallestFile = filesByLengDesc.Last
Console.WriteLine("The smallest file under {0} is {1} with a length of {2} bytes", _
root, smallestFile.FullName, smallestFile.Length)
' Return the FileInfos for the 10 largest files
' Based on a previous query, but nothing is executed
' until the For Each statement below.
Dim tenLargest = From file In filesByLengDesc Take 10
Console.WriteLine("The 10 largest files under {0} are:", root)
For Each fi As System.IO.FileInfo In tenLargest
Console.WriteLine("{0}: {1} bytes", fi.FullName, fi.Length)
Next
' Group files according to their size,
' leaving out the ones under 200K
Dim sizeGroups = From file As System.IO.FileInfo In fileList _
Where file.Length > 0 _
Let groupLength = file.Length / 100000 _
Group file By groupLength Into fileGroup = Group _
Where groupLength >= 2 _
Order By groupLength Descending
For Each group In sizeGroups
Console.WriteLine(group.groupLength + "00000")
For Each item As System.IO.FileInfo In group.fileGroup
Console.WriteLine(" {0}: {1}", item.Name, item.Length)
Next
Next
' Keep the console window open in debug mode
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
' This method is used to catch the possible exception
' that can be raised when accessing the FileInfo.Length property.
' In this particular case, it is safe to ignore the exception.
Function GetFileLength(ByVal fi As System.IO.FileInfo) As Long
Dim retval As Long
Try
retval = fi.Length
Catch ex As FileNotFoundException
' If a file is no longer present,
' just return zero bytes.
retval = 0
End Try
Return retval
End Function
End Module
하나 이상의 전체 FileInfo 개체를 반환하려면 먼저 쿼리에서 데이터 원본의 각 개체를 검사한 다음 Length 속성 값을 기준으로 정렬해야 합니다. 그런 다음 가장 긴 길이를 가진 단일 항목 또는 시퀀스를 반환할 수 있습니다. 목록의 첫 번째 요소를 반환하는 데 사용합니다 First . 처음 n 개수의 요소를 반환하는 데 사용합니다 Take . 목록의 시작 부분에 가장 작은 요소를 배치하려면 내림차순 정렬 순서를 지정합니다.
쿼리는 FileInfo 개체가 GetFiles
호출에서 생성된 이후, 다른 스레드에서 파일이 삭제된 경우 발생할 수 있는 예외를 처리하기 위해, 파일 크기를 바이트 단위로 가져오는 별도의 메서드를 호출합니다.
FileInfo 객체가 이미 생성된 경우에도, FileInfo 객체가 속성에 처음 접근할 때 가장 최신 바이트 단위의 크기를 사용하여 Length 속성을 새로 고치려 하기 때문에 예외가 발생할 수 있습니다. 이 작업을 쿼리 외부의 try-catch 블록에 배치하면 부작용을 일으킬 수 있는 쿼리에서 작업을 방지하는 규칙을 따릅니다. 일반적으로 애플리케이션이 알 수 없는 상태로 남아 있지 않도록 예외를 사용할 때는 주의해야 합니다.
코드 컴파일
Visual Basic 콘솔 애플리케이션 프로젝트를 만들어서, System.Linq 네임스페이스에 대한 Imports
문을 추가합니다.
참고하십시오
.NET