Click here to Skip to main content
Click here to Skip to main content

Print File Size

By , 18 Jul 2010
Rate this:
Please Sign up or sign in to vote.
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))

License

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

About the Author

chkmos

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. PinmemberNiklas Lindquist18-Jul-10 7:34 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 18 Jul 2010
Article Copyright 2010 by chkmos
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid