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]
[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)]
CFFCS | CarrzSynEdit: | ASP.NET (VB/C#)
public string FormatBytes(long bytes)
{
    string[] suffix = { "B", "KB", "MB", "GB", "TB", "PB" };
    int index = 0;
    double doubleBytes = bytes;

    // Loop and divide by 1024 until the value drops below 1024
    while (doubleBytes >= 1024 && index < suffix.Length - 1)
    {
        doubleBytes /= 1024.0;
        index++;
    }

    // Return the formatted string with 2 decimal places
    return string.Format("{0:0.00} {1}", doubleBytes, suffix[index]);
}

[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 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
}

[How I used it.]
[ASP.NET - CodeFile ascx.cs]
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 VB.NET (Bytes to KB, MB, GB)«