C# – Helper function to format file sizes
by admin on Sep.10, 2013, under Programming
I recently wanted to format filesizes to make them easier readable. The following code snippet contains the code I used to format the file sizes.
// Helper function to format the file size: string ffs(double size){ string prefix = " byte"; if(size > 1024){ size /= 1024D; prefix = " KB"; } if(size > 1024){ size /= 1024D; prefix = " MB"; } if(size > 1024){ size /= 1024D; prefix = " GB"; } return Math.Round(size, 2) + prefix; }
Below is a sample usage of the function above:
string formattedSize = ffs(new System.IO.FileInfo("hello.txt").Length); Console.WriteLine(formattedSize);
And the output looks like this:
17 byte