If you want to display the size of a file to the user simply doing the following will result in the size of the file in bytes:
new FileInfo(PathToMyFile).Length
However that's fairly useless in today's world of bigger and bigger files so along comes this neat bit of code:
public static string GetFileSizeAsString(long size)
{
double s = size;
string[] format = new string[] { "{0} bytes", "{0} KB", "{0} MB", "{0} GB", "{0} TB", "{0} PB", "{0} EB", "{0} ZB","{0} YB" };
int i = 0;
while (i < format.Length-1 && s >= 1024)
{
s = (int)(100 * s / 1024) / 100.0;
i++;
}
return string.Format(format[i], s.ToString("###,###,###.##"));
}
This will return you the following strings (depending on how big the file is...)
- 160 bytes
- 345 KB
- 34.7 MB
- 1.2 GB
- 1.76 TB
- 8.19 PB and so on...
If you get a file bigger than an 1,024 Yottabytes (YB) then tough! I'm sure you'll agree its not really that much of a limitation!