tôi cần phải tính toán kích thước thư mục trong VB NetCách tốt nhất để tính kích thước của một thư mục trong VB .NET là gì?
Tôi biết 2 phương pháp sau đây
Phương pháp 1: từ MSDN http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
'Ví dụ sau sẽ tính toán kích thước của một thư mục ' và các thư mục con của nó, nếu có, và hiển thị tổng kích thước 'tính theo byte.
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
Cách 2: từ 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()
Cả hai phương pháp hoạt động tốt. Tuy nhiên, họ mất rất nhiều thời gian để tính toán kích thước thư mục nếu có rất nhiều thư mục con. ví dụ: tôi có một thư mục với 150.000 thư mục con. Các phương pháp trên mất khoảng 1 giờ 30 phút để tính toán kích thước của thư mục. Tuy nhiên, nếu tôi kiểm tra kích thước từ cửa sổ phải mất chưa đầy một phút.
Vui lòng đề xuất các cách tốt hơn và nhanh hơn để tính kích thước của thư mục.
@ Magicprog.fr, vòng đẹp. Bạn có thể cho tôi biết thủ thuật đặt lại bộ đếm ở đây là gì? Tại sao nó vẫn trả về kích thước thư mục phù hợp với tất cả các thư mục con? Tôi chỉ không nhận được nó ... – LuckyLuke82