How to format bytes to human readable file size in C# and VB.NET

To format bytes to human readable file size you can use the following code snippet.

Sample C#

public static String FormatToHumanReadableFileSize(object value)
{
	try
	{
		string[] suffixNames = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
		var counter = 0;
		decimal dValue = 0;
		Decimal.TryParse(value.ToString(), out dValue);
		while (Math.Round(dValue / 1024) >= 1)
		{
			dValue /= 1024;
			counter++;
		}

		return string.Format("{0:n1} {1}", dValue, suffixNames[counter]);
	}
	catch(Exception ex)
	{
		//catch and handle the exception
		return string.Empty;
	}
}

Sample VB.NET

Public Shared Function FormatToHumanReadableFileSize(value As Object) As [String]
        Try
            Dim suffixNames As String() = {"bytes", "KB", "MB", "GB", "TB", "PB", _
                "EB", "ZB", "YB"}
            Dim counter = 0
            Dim dValue As Decimal = 0
            Decimal.TryParse(value.ToString(), dValue)
            While Math.Round(dValue / 1024) >= 1
                dValue /= 1024
                counter += 1
            End While

            Return String.Format("{0:n1} {1}", dValue, suffixNames(counter))
        Catch ex As Exception
            'catch and handle the exception
            Return String.Empty
        End Try
    End Function

Please Share us:
Please rate this snippet

One thought on “How to format bytes to human readable file size in C# and VB.NET

Leave a Reply