通过过滤器从文件夹中获取文件大小

Get file size from folder by filter

我正在使用 vb.net。 我想问一下如何通过过滤器获取每个文件的文件大小? 我想获取 .ts 文件的所有大小

这是我正在使用的代码

Dim TotalSize As Long = 0
Sub FileSize()
    Dim TheSize As Long = GetDirSize(txtPath.Text)

    TotalSize = 0 'Reset the counter

    If TheSize < 1024 Then
        lblSize.Text = Math.Round(TheSize, 0) & " B"
    ElseIf TheSize > 1024 AndAlso TheSize < (1024 ^ 2) Then
        lblSize.Text = Math.Round(TheSize / 1024, 1) & " KB"
    ElseIf TheSize > (1024 ^ 2) AndAlso TheSize < (1024 ^ 3) Then
        lblSize.Text = Math.Round(TheSize / 1024 / 1024, 1) & " MB"
    ElseIf TheSize > (1024 ^ 3) AndAlso TheSize < (1024 ^ 4) Then
        lblSize.Text = Math.Round(TheSize / 1024 / 1024 / 1024, 1) & " GB"
    End If
End Sub
Public Function GetDirSize(folder As String) As Long
    Dim FolderInfo = New DirectoryInfo(folder)
    For Each File In FolderInfo.GetFiles : TotalSize += File.Length
    Next
    For Each SubFolderInfo In FolderInfo.GetDirectories : GetDirSize(SubFolderInfo.FullName)
    Next
    Return TotalSize
End Function

您可以使用 DirectoryInfo.GetFiles() directly, specifying a filter SearchOption.AllDirectories 作为选项,这样您将解析指定路径中的所有子文件夹。

.Net Core 2.1+ 也有一个 EnumerationOptions class 和相应的 GetFiles() 重载。 class 允许收集更多与要执行的搜索相关的参数。

您可以简化一些事情并使用一种方法来接受执行此操作所需的所有参数:一个将显示结果的控件、要解析的路径和要设置的过滤器 ("*.ts"在这里,因为这是您发布的示例)。

SetControlTextToFileSize(label1, "C:\SomePath", "*.ts")

Helper 和 Worker 方法:

Private Sub SetControlTextToFileSize(ctrl As Control, folderPath As String, filter As String)
    Dim symbols As String() = {"", "K", "M", "G", "T", "P", "E", "Z", "Y"}

    Dim fileSize As ULong = TotalFoldersFileSize(folderPath, filter)
    If fileSize > 0 Then
        Dim lnSizeBase = CInt(Math.Truncate(Math.Log(fileSize, 1024)))
        Dim symbol = symbols(lnSizeBase)
        ctrl.Text = $"{fileSize / Math.Pow(1024, lnSizeBase):N2} {symbol}B"
    Else
        ctrl.Text = "0.00 B"
    End If
End Sub

Private Function TotalFoldersFileSize(folder As String, pattern As String) As ULong
    Return CULng(New DirectoryInfo(folder).
        GetFiles(pattern, SearchOption.AllDirectories).Sum(Function(f) CULng(f.Length)))
End Function

扩展 形式的最后一个方法,以防它更可取:

Private Function TotalFoldersFileSize(folder As String, pattern As String) As ULong
    Dim totalSize As ULong

    Dim folderInfo = New DirectoryInfo(folder).GetFiles(pattern, SearchOption.AllDirectories)
    For Each fInfo As FileInfo In folderInfo
        totalSize += CULng(fInfo.Length)
    Next
    Return totalSize
End Function