Click here to Skip to main content
15,882,658 members
Articles / Programming Languages / Visual Basic

Print File Size

Rate me:
Please Sign up or sign in to vote.
3.50/5 (3 votes)
18 Jul 2010CPOL 13.8K   4   1
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")


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

Written By
Hong Kong Hong Kong
I loves Microsoft .NET.
I develop both windows and ASP.NET application using VB.NET and C#.

Comments and Discussions

GeneralFormatFileSize might have been a better name. Pin
Niklas L18-Jul-10 7:34
Niklas L18-Jul-10 7:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.