我需要在VB的.Net计算目录大小在VB .NET中计算目录大小的最佳方法是什么?
我知道以下2种方法
方法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分钟来计算目录的大小。但是,如果我从窗口检查大小,则需要不到一分钟的时间。
请建议更好更快的方法来计算目录的大小。
@ Magicprog.fr,漂亮的循环得到总大小。你能告诉我在这里重置柜台的诀窍是什么?为什么它仍然返回所有子文件夹的正确文件夹大小?我只是不明白... – LuckyLuke82 2017-01-09 16:54:51