An example on how to format file size in C#
Unfortunately, there is not a function in .NET that will do this for you, so here is an example on how you could do it :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class FileHelper { private static readonly long kilobyte = 1024; private static readonly long megabyte = 1024 * kilobyte; private static readonly long gigabyte = 1024 * megabyte; private static readonly long terabyte = 1024 * gigabyte; public static string ToByteString(long bytes) { if (bytes > terabyte) return (bytes / terabyte).ToString("0.00 TB"); else if (bytes > gigabyte) return (bytes / gigabyte).ToString("0.00 GB"); else if (bytes > megabyte) return (bytes / megabyte).ToString("0.00 MB"); else if (bytes > kilobyte) return (bytes / kilobyte).ToString("0.00 KB"); else return bytes + " Bytes"; } } |
Nice code snippet.
I noticed one slight inconsitency. Your argument to ToString suggest that you want to format the number to 2 decimal places but because your divide is in integer arithmetic you have lost this information. The decimal places will always read “.00″. I suggest either:
(a) Convert your division to floating point arithmetic. E.g.
if (bytes > terabyte) return (bytes / (double)terabyte).ToString(”0.00 TB”);
(b) Drop the decimal places. E.g.
if (bytes > terabyte) return (bytes / terabyte).ToString(”0 TB”);
I changed all of the longs to floats and this works great. I added it to the FileHelpers class I already had and it is a great fit.
Thank You