다음을 통해 공유


방법: 폴더 집합의 총 바이트 수 쿼리(LINQ)(Visual Basic)

이 예제에서는 지정된 폴더의 모든 파일과 모든 하위 폴더에서 사용되는 총 바이트 수를 검색하는 방법을 보여 있습니다.

예시

이 메서드는 Sum 절에서 select 선택한 모든 항목의 값을 추가합니다. 이 쿼리를 쉽게 수정하여 지정된 디렉터리 트리에서 가장 크고 작은 파일을 검색하려면 대신 Min또는 Max 메서드를 Sum 호출할 수 있습니다.

Module QueryTotalBytes  
    Sub Main()  
  
        ' Change the drive\path if necessary.  
        Dim root As String = "C:\Program Files\Microsoft Visual Studio 9.0\VB"  
  
        'Take a snapshot of the folder contents.  
        ' This method assumes that the application has discovery permissions  
        ' for all folders under the specified path.  
        Dim fileList = My.Computer.FileSystem.GetFiles _  
                  (root, FileIO.SearchOption.SearchAllSubDirectories, "*.*")  
  
        Dim fileQuery = From file In fileList _  
                        Select GetFileLength(file)  
  
        ' Force execution and cache the results to avoid multiple trips to the file system.  
        Dim fileLengths = fileQuery.ToArray()  
  
        ' Find the largest file  
        Dim maxSize = Aggregate aFile In fileLengths Into Max()  
  
        ' Find the total number of bytes  
        Dim totalBytes = Aggregate aFile In fileLengths Into Sum()  
  
        Console.WriteLine("The largest file is " & maxSize & " bytes")  
        Console.WriteLine("There are " & totalBytes & " total bytes in " & _  
                          fileList.Count & " files under " & root)  
  
        ' 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.  
    Function GetFileLength(ByVal filename As String) As Long  
        Dim retval As Long  
        Try  
            Dim fi As New System.IO.FileInfo(filename)  
            retval = fi.Length  
        Catch ex As System.IO.FileNotFoundException  
            ' If a file is no longer present,  
            ' just return zero bytes.
            retval = 0  
        End Try  
  
        Return retval  
    End Function  
End Module  

지정된 디렉터리 트리에서 바이트 수만 계산해야 하는 경우 LINQ 쿼리를 만들지 않고도 이 작업을 보다 효율적으로 수행할 수 있으므로 목록 컬렉션을 데이터 원본으로 만드는 오버헤드가 발생합니다. 쿼리가 더 복잡해지거나 동일한 데이터 원본에 대해 여러 쿼리를 실행해야 하는 경우 LINQ 접근 방식의 유용성이 증가합니다.

쿼리는 파일 길이를 얻기 위해 별도의 메서드를 호출합니다. 다른 스레드에서 파일이 삭제된 후 FileInfo 객체가 GetFiles 호출에서 생성되었을 때 발생할 수 있는 예외를 처리하기 위해 이 작업을 수행합니다. FileInfo 객체가 이미 생성되었더라도, FileInfo 객체가 Length 속성에 처음 액세스할 때 가장 최신 길이로 이 속성을 새로 고치려고 시도하기 때문에 예외가 발생할 수 있습니다. 이 작업을 쿼리 외부의 try-catch 블록에 배치하면 코드는 부작용을 일으킬 수 있는 쿼리에서 작업을 방지하는 규칙을 따릅니다. 일반적으로 애플리케이션이 알 수 없는 상태로 남아 있지 않은지 확인하기 위해 예외를 사용할 때는 주의해야 합니다.

코드 컴파일

Visual Basic 콘솔 애플리케이션 프로젝트를 만들어서, System.Linq 네임스페이스에 대한 Imports 문을 추가합니다.

참고하십시오