在VB .NET中计算目录大小的最佳方法是什么?

时间:2010-07-08 23:24:53

标签: vb.net directory size

我需要在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分钟来计算目录的大小。但是,如果我从窗口检查尺寸,则需要不到一分钟的时间。

请建议更好,更快的方法来计算目录的大小。

7 个答案:

答案 0 :(得分:5)

并行工作应该让它更快,至少在多核机器上。试试这个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; 
} 

答案 1 :(得分:3)

Though this answer is talking about Python,这个概念也适用于此。

Windows资源管理器以递归方式使用系统API调用FindFirstFileFindNextFile来提取文件信息,然后可以通过struct传递的数据非常快速地访问文件大小,{ {1}}:http://msdn.microsoft.com/en-us/library/aa365740(v=VS.85).aspx

我的建议是使用P / Invoke实现这些API调用,我相信您将获得显着的性能提升。

答案 2 :(得分:2)

这是一个简短而又甜蜜的代码片段,可以完成工作。您只需在调用函数

之前重置计数器
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

答案 3 :(得分:1)

非常感谢@Jamie的代码和@Mathiasfk的翻译成VB.net。我将其用于我自己的备份程序,该程序在默认设置下仅备份整个配置文件文件夹,这是一个最终可以理解接合点并读取或多或少正确大小的代码。备份至少可以。 :-)

我只需要将代码放入“尝试”中,这样​​就不会停止它无法访问的文件夹,如果您也可能遇到此类问题,请使用此选项(不处理错误,请跳过它,可以如果对您很重要,请添加):

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

这是我能得到它的简短。

它将在消息框中显示所选内容的大小。 您需要在表单中使用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

答案 6 :(得分:0)

尝试此操作以获得GB的总大小

    Dim fso = CreateObject("Scripting.FileSystemObject")
    Dim profile = fso.GetFolder("folder_path")
    MsgBox(profile.Size / 1073741824)