[英]What’s the best way to calculate the size of a directory in VB .NET?
我需要計算 VB.Net 中的目錄大小
我知道以下兩種方法
方法一:來自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
方法二:從.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 分鍾來計算目錄的大小。 但是,如果我檢查 windows 的大小,則需要不到一分鍾的時間。
請建議更好更快的計算目錄大小的方法。
並行工作應該更快,至少在多核機器上。 試試這個C#代碼。 你將不得不翻譯為VB.NET。
private static long DirSize(string sourceDir, bool recurse)
{
long size = 0;
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
Interlocked.Add(ref size, (new FileInfo(fileName)).Length);
}
if (recurse)
{
string[] subdirEntries = Directory.GetDirectories(sourceDir);
Parallel.For<long>(0, subdirEntries.Length, () => 0, (i, loop, subtotal) =>
{
if ((File.GetAttributes(subdirEntries[i]) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
subtotal += DirSize(subdirEntries[i], true);
return subtotal;
}
return 0;
},
(x) => Interlocked.Add(ref size, x)
);
}
return size;
}
雖然這個答案是關於Python的 ,但這個概念也適用於此。
Windows資源管理器以遞歸方式使用系統API調用FindFirstFile
和FindNextFile
來提取文件信息,然后通過struct
WIN32_FIND_DATA
傳回的數據可以非常快速地訪問文件大小: http : //msdn.microsoft.com/en-us/ library / aa365740(v = VS.85).aspx 。
我的建議是使用P / Invoke實現這些API調用,我相信您將獲得顯着的性能提升。
這是一個簡短而又甜蜜的代碼片段,可以完成工作。 您只需在調用該函數之前重置計數器
Public Class Form1
Dim TotalSize As Long = 0
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
TotalSize = 0 'Reset the counter
Dim TheSize As Long = GetDirSize("C:\Test")
MsgBox(FormatNumber(TheSize, 0) & " Bytes" & vbCr & _
FormatNumber(TheSize / 1024, 1) & " Kilobytes" & vbCr & _
FormatNumber(TheSize / 1024 / 1024, 1) & " Megabytes" & vbCr & _
FormatNumber(TheSize / 1024 / 1024 / 1024, 1) & " Gigabytes")
End Sub
Public Function GetDirSize(RootFolder As String) As Long
Dim FolderInfo = New IO.DirectoryInfo(RootFolder)
For Each File In FolderInfo.GetFiles : TotalSize += File.Length
Next
For Each SubFolderInfo In FolderInfo.GetDirectories : GetDirSize(SubFolderInfo.FullName)
Next
Return TotalSize
End Function
End Class
非常感謝@Jamie for Code和@Mathiasfk轉換為VB.net。 我將它用於我自己的備份程序,在默認設置中只備份整個配置文件夾,它是一個代碼,最終也能夠理解連接點並讀取或多或少正確的大小。 這對Backup來說至少沒問題。 :-)
我只是把代碼放在Try中,所以它不會停止它無法訪問的文件夾,如果你也可以有這樣的問題只是使用它(不處理錯誤只是跳過它,你可以添加,如果重要為了你):
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Public Function GetFolderSize(ByVal path As String, Optional recurse As Boolean = True) As Long
Dim totalSize As Long = 0
Try
Dim files() As String = Directory.GetFiles(path)
Parallel.For(0, files.Length,
Sub(index As Integer)
Dim fi As New FileInfo(files(index))
Dim size As Long = fi.Length
Interlocked.Add(totalSize, size)
End Sub)
Catch ex As Exception
End Try
Try
If recurse Then
Dim subDirs() As String = Directory.GetDirectories(path)
Dim subTotal As Long = 0
Parallel.For(0, subDirs.Length,
Function(index As Integer)
If (File.GetAttributes(subDirs(index)) And FileAttributes.ReparsePoint) <> FileAttributes.ReparsePoint Then
Interlocked.Add(subTotal, GetFolderSize(subDirs(index), True))
Return subTotal
End If
Return 0
End Function)
Interlocked.Add(totalSize, subTotal)
End If
Catch ex As Exception
End Try
Return totalSize
End Function
VB代碼基於Jamie的回答:
Imports System.Threading
Imports System.IO
Public Function GetDirectorySize(ByVal path As String, Optional recurse As Boolean = False) As Long
Dim totalSize As Long = 0
Dim files() As String = Directory.GetFiles(path)
Parallel.For(0, files.Length,
Sub(index As Integer)
Dim fi As New FileInfo(files(index))
Dim size As Long = fi.Length
Interlocked.Add(totalSize, size)
End Sub)
If recurse Then
Dim subDirs() As String = Directory.GetDirectories(path)
Dim subTotal As Long = 0
Parallel.For(0, subDirs.Length,
Function(index As Integer)
If (File.GetAttributes(subDirs(index)) And FileAttributes.ReparsePoint) <> FileAttributes.ReparsePoint Then
Interlocked.Add(subTotal, GetDirectorySize(subDirs(index), True))
Return subTotal
End If
Return 0
End Function)
Interlocked.Add(totalSize, subTotal)
End If
Return totalSize
End Function
在這里,我可以得到它。
它將在消息框中顯示所選的大小。 您需要在表單中使用FolderBrowserDialog
才能使用它。
Class Form1
Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
Else : End
End If
Dim dInfo As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
Dim sizeOfDir As Long = DirectorySize(dInfo, True)
MsgBox("Showing Directory size of " & FolderBrowserDialog1.SelectedPath _
& vbNewLine & "Directory size in Bytes : " & "Bytes " & sizeOfDir _
& vbNewLine & "Directory size in KB : " & "KB " & Math.Round(sizeOfDir / 1024, 3) _
& vbNewLine & "Directory size in MB : " & "MB " & Math.Round(sizeOfDir / (1024 * 1024), 3) _
& vbNewLine & "Directory size in GB : " & "GB " & Math.Round(sizeOfDir / (1024 * 1024 * 1024), 3))
Catch ex As Exception
End Try
End Sub
Private Function DirectorySize(ByVal dInfo As IO.DirectoryInfo, ByVal includeSubDir As Boolean) As Long
Dim totalSize As Long = dInfo.EnumerateFiles().Sum(Function(file) file.Length)
If includeSubDir Then totalSize += dInfo.EnumerateDirectories().Sum(Function(dir) DirectorySize(dir, True))
Return totalSize
End Function
End Class
試試這個以獲得GB的總大小
Dim fso = CreateObject("Scripting.FileSystemObject")
Dim profile = fso.GetFolder("folder_path")
MsgBox(profile.Size / 1073741824)
這是我認為最好的方法。
Imports System.IO
Public Class FolderSizeCalculator
Public Shared Function GetFolderSize(ByVal folderPath As String) As Long
Dim size As Long = 0
Try
Dim files As String() = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories)
For Each file As String In files
Dim fileInfo As New FileInfo(file)
size += fileInfo.Length
Next
Catch ex As Exception
' Handle any exceptions that may occur
End Try
Return size
End Function
End Class
您可以調用 GetFolderSize() 方法並傳入要計算其大小的文件夾的路徑,它將以字節為單位返回大小。
你可以像這樣使用它:
Dim folderSize As Long = FolderSizeCalculator.GetFolderSize("C:\MyFolder")
Console.WriteLine("Folder size: " & folderSize & " bytes")
..請注意,如果運行應用程序的用戶沒有讀取文件夾或子文件夾的權限,此方法將失敗,您可以使用 try catch 塊來處理
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.