When working with file uploads, storage tracking, or database logging in VB.NET, file sizes are inherently stored as raw integers representing bytes. Displaying a number like "5371924051" to an end-user creates a poor user experience.
This article provides a clean, reusable VB.NET function that dynamically scales any byte value into its optimal human-readable unit (Bytes, KB, MB, GB, or TB), rounded to two decimal places. It also covers safe type casting from database objects (rs) and conditional error handling to protect your applications from crashing on DBNull values.
[What It Is Used For]

This solution transforms unformatted, large numeric byte values into a clean, human-readable string. Instead of forcing users to mentally calculate commas and zeros, it automatically determines whether a file size is best represented in Kilobytes (KB), Megabytes (MB), Gigabytes (GB), or Terabytes (TB), and appends the correct text suffix.
[When to Use It]
[How to Use It]
Place this logic inside your control file so it can be called from anywhere within the class:
[ASP.NET - Step 1: Add the Reusable Function to your Code-Behind (.ascx.vb)]
CFFCS | CarrzSynEdit: | ASP.NET (VB/C#)
Public Function FormatBytes(ByVal bytes As Long) As String
    Dim suffix() As String = {"B", "KB", "MB", "GB", "TB", "PB"}
    Dim index As Integer = 0
    Dim doubleBytes As Double = bytes

    ' Keep dividing by 1024 until the value fits the largest matching unit
    While doubleBytes >= 1024 AndAlso index < suffix.Length - 1
        doubleBytes /= 1024.0
        index += 1
    End While

    ' Return formatted string with exactly 2 decimal places
    Return String.Format("{0:0.00} {1}", doubleBytes, suffix(index))
End Function

[ASP.NET - Step 2: Bind the Database Value to Your UI Label Safely]
When reading from a database recordset object, always check for DBNull
Copy
Search Site
Search Google
values before casting the data to a numeric Long
Copy
Search Site
Search Google
(Int64
Copy
Search Site
Search Google
). This prevents your page from throwing an unhandled exception if a file size is missing.
CFFCS | CarrzSynEdit: | ASP.NET (VB/C#)
' Check if the database field contains data
If rs("FileSize") IsNot Nothing AndAlso Not IsDBNull(rs("FileSize")) Then
    ' Convert database object to Int64 (Long), pass to function, and update UI
    FileSize.Text = FormatBytes(Convert.ToInt64(rs("FileSize")))
Else
    ' Fallback fallback display if the database record is empty
    FileSize.Text = "0.00 B"
End If

[How I used it.]
[ASP.NET - ASP.NET - CodeFile ascx.vb]
CFFCS | CarrzSynEdit: | ASP.NET (VB/C#)
FileSize.Text = FormatBytes(Convert.ToInt64(rs("FileSize")))

[HTML - FrontEnd .ascx]
CFFCS | CarrzSynEdit: | HTML (Hyper Text Markup Language)
<div class="stat">
<span>Size</span><strong><asp:Label ID="FileSize" runat="server" /></strong>
</div>

Other Articles Related to this Entry.Formatting File Sizes Dynamically in C#.NET (Bytes to KB, MB, GB)«