我有一个列表视图,显示文件夹和文件,我可以显示文件和子文件夹的大小,但我如何使用不包含父/根文件夹的子文件夹。
修改
例如,如果Folder1
的尺寸为10 MB
并且SubFolder
的尺寸为20 MB
且总共30 MB
,那么在SubFolder
中显示20 MB
的内容时,应该只获得Folder1
ListView
的大小。
Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
Dim Size As Long = 0
Dim dis As DirectoryInfo() = d.GetDirectories()
Dim di As DirectoryInfo
For Each di In dis
Size += DirSize(di)
Next di
Return Size
End Function
我的列表视图代码:
Sub lv1items()
ListView1.Items.Clear()
Dim fPath As String = Form2.TextBox1.Text
Dim di = New DirectoryInfo(fPath)
' store imagelist index for known/found file types
Dim exts As New Dictionary(Of String, Int32)
If di.Exists = False Then
MessageBox.Show("Destination path" & " " & Form2.TextBox1.Text & " is not found.", "Directory Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form2.Show()
Else
Dim img As Image
Dim lvi As ListViewItem
For Each d In di.EnumerateDirectories("*.*", SearchOption.TopDirectoryOnly)
lvi = New ListViewItem(d.Name)
lvi.SubItems.Add(DirSize(di).ToString("0.00") & " MB")
lvi.SubItems.Add(d.CreationTime.Date)
ListView1.Items.Add(lvi)
img = NativeMethods.GetShellIcon(d.FullName)
ImageList1.Images.Add(img)
lvi.ImageIndex = ImageList1.Images.Count - 1
Next
End Sub
请帮忙一点?
答案 0 :(得分:2)
您可以使用此功能:
Public Function GetDirectorySize(path As String) As Long
Dim files() As String = Directory.GetFiles(path, "*", SearchOption.AllDirectories)
Dim size As Long = 0
For Each file As String In files
Dim info As New FileInfo(file)
size += info.Length
Next
Return size
End Function
请注意,这会检查文件夹及其子目录中每个文件的大小。因此,保证返回正确的大小。
证明它有效:
根:
子文件夹:
总大小=(1483 + 25315)* 1024 = 274411152字节。
节目输出:
27440016字节≈274411152字节。
注意: 存在差异,因为Windows资源管理器会舍入一些字节以显示KB。如果您查看每个文件的属性并加起来,那么您将从资源管理器和函数中获得相同的大小。