The nice thing about programming is, that repetative tasks can be automated. A solution that automatically calculates the size could be:
- find file size
- repeat until size is bigger than 1024
- divide size by 1024
- store size position
- loop
The code can look like this:
private String sizeFormatter(Int64 filesize)
{
var sizes = new List<String> { "B", "KB", "MB", "GB", "TB", "PB" };
var size = 0;
while (filesize > 1024)
{
filesize /= 1024;
size++;
}
return String.Format("{0}{1}", filesize, sizes[size]);
}
And the usage:
var bigFile = new FileInfo("C:\\oracle\\OracleXE112_Win32.zip");
var smallFile = new FileInfo("C:\\oracle\\ScriptCreateUser.sql");
var verySmallFile = new FileInfo("C:\\ScriptCreateTable.sql");
Console.WriteLine(sizeFormatter(bigFile.Length));
Console.WriteLine(sizeFormatter(smallFile.Length));
Console.WriteLine(sizeFormatter(verySmallFile.Length));
The output is:
312MB
12KB
363B
This method could be optimized regarding accuracy, but for the general usage it should be alright.