加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-17 00:31:00 所属栏目:大数据 来源:网络整理
导读:我需要在VB .Net中计算目录大小 我知道以下两种方法 方法1:来自MSDN http://msdn.microsoft.com/en-us/library/system.io.directory.aspx ‘以下示例计算目录的大小 ‘及其子目录(如果有),并显示总大小 ‘以字节为单位. Imports SystemImports System.IOPub
我需要在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分钟来计算目录的大小.但是,如果我从窗户检查尺寸不到一分钟.

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读