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]
File Upload Controls: Displaying the size of a file a user just uploaded in an ASP.NET Web Form (.ascx or .aspx).
Document Management Systems: Listing files stored in a database alongside their respective sizes.
Storage Dashboards: Showing server space, user quotas, or remaining disk capacity.
Data-Driven Grids: Any time you are looping through a database recordset (rs or DataRow) and outputting a FileSize column to a User Interface (UI) label or textbox.
[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)]
Public Function FormatBytes(ByVal bytes AsLong) AsStringDim suffix() AsString = {"B", "KB", "MB", "GB", "TB", "PB"}
Dim index AsInteger = 0
Dim doubleBytes AsDouble = 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
ReturnString.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.
' 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