【问题标题】:Get file size from folder by filter通过过滤器从文件夹中获取文件大小
【发布时间】:2020-05-16 06:16:56
【问题描述】:

我正在使用 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

【问题讨论】:

  • 如果您的问题真的不需要回答,那么您应该删除它。如果值得回答但您自己提供了答案,您应该发布答案并接受它,而不是发表评论。这样,每个人都可以看到问题已经得到解答,而无需打开它并先阅读它。也就是说,我不能 100% 确定您不需要特定数量的声望点来执行这些操作。

标签: vb.net file directoryinfo


【解决方案1】:

您可以直接使用DirectoryInfo.GetFiles(),指定过滤器SearchOption.AllDirectories 作为选项,这样您将解析指定路径中的所有子文件夹。

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

您可以简化一些事情并使用一种方法来接受执行此操作所需的所有参数:一个将显示结果的控件、要解析的路径和要设置的过滤器(此处为"*.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

【讨论】:

    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多