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 = (100 * s / 1024) / 100.0;
       i++;
    }
return string.Format(format[i], s.ToString("###,###,##0.##")); }

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 ;)

NOTE: Thanks to David's comment I've updated the above code, previously I was casting to an (int) causing incorrect results...

NOTE: Thanks again to David, I've now changed the output to cater for 0 bytes...


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

Comments

Gravatar
# 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. =)
Gravatar
# re: C#: Getting a user friendly file size as a string
Posted by David Cumps
on 8/27/2008 9:54 AM
This gives incorrect results due to the int overflowing.

For example, try size = 249884004352

It gives -21.474.836,48 KB as result.

If you change your code and get rid of the (int) cast, you get 232,72 GB :)

Very useful otherwise, just what I needed!
Gravatar
# re: C#: Getting a user friendly file size as a string
Posted by David Cumps
on 8/27/2008 10:07 AM
Also, when you try to output 0, you get " bytes", if you change your format to:

return string.Format(format[i], s.ToString("###,###,##0.##"));

you'll get "0 bytes".

I've used your code at http://wiki.cumps.be/learning/exam70-536/driveinfo (with credits :p)

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 7 and 2 and type the answer here: