窗体上添加一个按钮,代码如下:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Text = "稍等!"
Button1.Enabled = False
Dim MyFolder As String = "C:\Windows"
Dim MyDir As New System.IO.DirectoryInfo(MyFolder)
Dim MyInfo As String = MyFolder + "文件夹的大小是:" + CalculateDirectorySize(MyDir, True).ToString() + "字节。"
MessageBox.Show(MyInfo, "信息提示", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Button1.Text = "开始"
Button1.Enabled = True
End Sub
Public Shared Function CalculateDirectorySize(ByVal MyDirectory As System.IO.DirectoryInfo, ByVal IsSubDirectories As Boolean) As Long
Dim MySize As Long = 0
'检查包含的所有文件
Dim MyFiles() As System.IO.FileInfo = MyDirectory.GetFiles()
For Each MyFile As System.IO.FileInfo In MyFiles
MySize += MyFile.Length
Next
'检查包含的所有子文件夹
If (IsSubDirectories) Then
Dim MyDirs() As System.IO.DirectoryInfo = MyDirectory.GetDirectories()
For Each MyDir As System.IO.DirectoryInfo In MyDirs
MySize += CalculateDirectorySize(MyDir, True)
Next
End If
Return MySize
End Function
End Class
类库里File和Dir都没有直接获取文件夹大小的方法。如果不用FSO的话,要编程实现;
代码如下
Import system.io
Function GetFolderSize(ByVal DirPath As String, _
Optional IncludeSubFolders as Boolean = True) As Long
Dim lngDirSize As Long
Dim objFileInfo As FileInfo
Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)
Dim objSubFolder As DirectoryInfo
Try
'add length of each file
For Each objFileInfo In objDir.GetFiles()
lngDirSize += objFileInfo.Length
Next
'call recursively to get sub folders
'if you don't want this set optional
'parameter to false
If IncludeSubFolders then
For Each objSubFolder In objDir.GetDirectories()
lngDirSize += GetFolderSize(objSubFolder.FullName)
Next
End if
Catch Ex As Exception
Ex.tostring
End Try
Return lngDirSize
End Function