這個範例示範如何擷取指定資料夾中所有檔案及其所有子資料夾中所使用的位元組總數。
範例
方法 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中建立物件後,如果檔案在另一個線程上被刪除時可能發生的例外狀況。 即使 FileInfo 對象已經建立,也會發生例外狀況,因為 FileInfo 物件會在第一次存取屬性時嘗試以最新的長度重新整理其 Length 屬性。 藉由將這項作業放在查詢外部的 try-catch 區塊中,程式代碼會遵循規則,避免在可能導致副作用的查詢中執行作業。 一般而言,當您取用例外狀況時,必須非常小心,以確保應用程式不會處於未知狀態。
編譯程式碼
建立一個包含 Imports 語句以使用 System.Linq 命名空間的 Visual Basic 控制台應用程式專案。