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!


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Thursday, January 24, 2008 1:52 PM | in .NET C#

Comments

# re: C#: Getting a user friendly file size as a string
Posted by Dana
on 6/18/2008 12:01 PM
That's rather clever, and handy. Just what I was looking for - thank you. =)

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 6 and 3 and type the answer here: