Print File Size
The following function allows you to print the file size, given the number of bytes, which is obtained from the FileInfo.Length property.
The function always print the size in 2 decimal digits and will automatically determine the correct layman unit label.
Public Shared Function PrintFileSize(ByVal size As Long) As String
Dim unit As String
Dim d As Double
Select Case size
Case Is < 1024
d = size
unit = "B"
Case Is < 1048576 '~1K
d = System.Math.Round(size / 1024, 2)
unit = "KB"
Case Is < 1073741824 '~1MB
d = System.Math.Round(size / 1048576, 2)
unit = "MB"
Case Is < 1099511627776 '~1GB
d = System.Math.Round(size / 1073741824, 2)
unit = "GB"
Case Else
d = System.Math.Round(size / 1099511627776, 2)
unit = "TB"
End Select
Return d.ToString("0.00") & unit
End Function
The following is the example on printing the file size of notepad.exe.
Dim fi As New System.IO.FileInfo("C:\Windows\notepad.exe")
MessageBox.Show(PrintFileSize(fi.Length))