When working with file uploads, storage tracking, or database logging in C#.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 C#.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.cs)]
// Check if the database field is valid and not null
if (rs["FileSize"] != null && rs["FileSize"] != DBNull.Value)
{
// Convert to long, format, and assign to the text property
FileSize.Text = FormatBytes(Convert.ToInt64(rs["FileSize"]));
}
else
{
FileSize.Text = "0.00 B"; // Fallback value
}