ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

FormatSize

Nicely formatted file size. This method will return file size with bytes, KB, MB and GB in it. You can use this alongside the Extension method named FileSize.

Source

public static string FormatFileSize(this long fileSize)
{
	string[] suffix = { "bytes", "KB", "MB", "GB" };
	long j = 0;

	while (fileSize > 1024 && j < 4)
	{
		fileSize = fileSize / 1024;
		j++;
	}
	return (fileSize + " " + suffix[j]);
}

Example

// Using another Extension Method: FileSize to get the size of the file
string path = @"D:\WWW\Proj\web.config";
Console.WriteLine("File Size is: {0}.", path.FileSize().FormatSize());

Author: Earljon Hidalgo

Submitted on: 26 mrt 2008

Language: C#

Type: System.String

Views: 6243