C#: Getting a user friendly file size as a string

by Brad 24. January 2008 13:52

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...

Tags:

C#

Comments

6/18/2008 11:01:17 AM #

That's rather clever, and handy.  Just what I was looking for - thank you. =)

Dana |

8/27/2008 8:54:48 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 Smile

Very useful otherwise, just what I needed!

David Cumps |

8/27/2008 9:07:23 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)

David Cumps |

8/2/2009 1:29:55 PM #

Hi. I realise this is a year old, but in the larger chunk of code, how do I link it up to a file in C#?
Sorry if there is a simple answer, I'm a beginner Smile

Jonathan Tiney |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar