我需要在VB .Net中计算目录大小
我知道以下两种方法
方法1:来自MSDN http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
‘以下示例计算目录的大小
‘及其子目录(如果有),并显示总大小
‘以字节为单位.
- Imports System
- Imports System.IO
- Public Class ShowDirSize
- Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
- Dim Size As Long = 0
- ' Add file sizes.
- Dim fis As FileInfo() = d.GetFiles()
- Dim fi As FileInfo
- For Each fi In fis
- Size += fi.Length
- Next fi
- ' Add subdirectory sizes.
- Dim dis As DirectoryInfo() = d.GetDirectories()
- Dim di As DirectoryInfo
- For Each di In dis
- Size += DirSize(di)
- Next di
- Return Size
- End Function 'DirSize
- Public Shared Sub Main(ByVal args() As String)
- If args.Length <> 1 Then
- Console.WriteLine("You must provide a directory argument at the command line.")
- Else
- Dim d As New DirectoryInfo(args(0))
- Dim dsize As Long = DirSize(d)
- Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.",d,dsize)
- End If
- End Sub 'Main
- End Class 'ShowDirSize
方法2:从What’s the best way to calculate the size of a directory in .NET?开始
- Dim size As Int64 = (From strFile In My.Computer.FileSystem.GetFiles(strFolder,_
- FileIO.SearchOption.SearchAllSubDirectories) _
- Select New System.IO.FileInfo(strFile).Length).Sum()
这两种方法都很好.但是,如果存在大量子文件夹,则需要花费大量时间来计算目录大小.例如,我有一个包含150,000个子文件夹的目录.上述方法花了大约1小时30分钟来计算目录的大小.但是,如果我从窗户检查尺寸不到一分钟.
请建议更好,更快的方法来计算目录的大小.
Though this answer is talking about Python,这个概念也适用于此.
Windows资源管理器以递归方式使用系统API调用FindFirstFile和FindNextFile来提取文件信息,然后可以通过结构WIN32_FIND_DATA:http://msdn.microsoft.com/en-us/library/aa365740(v=VS.85).aspx传回的数据非常快速地访问文件大小.