Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Print File Size

3.50/5 (3 votes)
18 Jul 2010CPOL 14.3K  
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.

VB
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.
VB
Dim fi As New System.IO.FileInfo("C:\Windows\notepad.exe")
MessageBox.Show(PrintFileSize(fi.Length))

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)