此示例演示如何检索指定文件夹及其所有子文件夹中所有文件使用的字节总数。
示例:
该方法在Sum子句中,将所有选择项的值相加。 可以通过调用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 控制台应用程序项目,其中包含 Imports
System.Linq 命名空间的语句。