Home

VB.NET Format File Size

Posted by SteveHardie | On: Oct 07 2009

Format a large integer (long) that represents a file size in bytes to a more readable string representation that includes Kb, Mb and Gb.

    Public Shared Function FormatFileSize(ByVal FileSizeBytes As Long) As String
        Dim sizeTypes() As String = {"b", "Kb", "Mb", "Gb"}
        Dim Len As Decimal = FileSizeBytes
        Dim sizeType As Integer = 0
        Do While Len > 1024
            Len = Decimal.Round(Len / 1024, 2)
            sizeType += 1
            If sizeType >= sizeTypes.Length - 1 Then Exit Do
        Loop

        Dim Resp As String = Len.ToString & " " & sizeTypes(sizeType)
        Return Resp
    End Function

1 Comment

  1. Toby says:

    Exactly what I was looking for. Thanks

Leave a comment