有时候我们需要获得某个文件或者文件夹的大小,以下的两个函数在vb.net中相对完美的解决了这个问题,供参考
Public Function GetFolderSize(ByVal DirPath As String, Optional ByVal 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
Public Function GetFileSize(ByVal fileName As String) As Single '获取指定文件大小
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(Application.StartupPath & "\" & fileName & ".mdb")
Return infoReader.Length
' MsgBox("文件大小为: " & infoReader.Length & " bytes.")
End Function