beta.blog

C# – Helper function to format file sizes

by 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


Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!