How to get the current Database and Log Filesize using MSSQL

To get the current Database and Log Filesize using MSSQL you can use the snippet below. Tested using SQL Server 2012.

Sample MSSQL

with database_files_CTE as
(
    select
        name, type_desc, physical_name, size_mb = convert(decimal(11, 2), size * 8.0 / 1024),
        space_used_mb = convert(decimal(11, 2), fileproperty(name, 'spaceused') * 8.0 / 1024) from sys.database_files
)
select name,type_desc as [type],physical_name as [path],size_mb as [Filesize],space_used_mb as [Filesize used],
case size_mb when 0 then 0 else convert(decimal(5, 2), space_used_mb / size_mb * 100) end as [Filesize used %]  from database_files_CTE;

Sample Output

Query Results Filesizes

Please rate this snippet

How to convert bytes to human readable file size in PHP

To convert bytes to human readable file size in PHP you can use the following snippet.

Sample PHP

function BytesToHumanReadableSize($bytes)
{
	$unit = null;
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
	
	for($Counter = 0, $c = count($units); $Counter < $c; $Counter++)
	{
		if ($bytes > 1024)
		{
			$bytes = $bytes / 1024;
		}
		else
		{
			$unit = $units[$Counter];
			break;
		}
	}
 
	return round($bytes, 2). ' ' .$unit;
}

Please rate this snippet

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 rate this snippet