orilon

C# Get the readable filesize of Int32/Int64 value

Jun 4th, 2012
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.76 KB | None | 0 0
  1. /// get file size from Int32 / In64 value.
  2.  
  3. public static string ToFileSize(this int source)
  4. {
  5.     return ToFileSize(Convert.ToInt64(source));
  6. }
  7. public static string ToFileSize(this long source)
  8. {
  9.     const int byteConversion = 1024;
  10.     double bytes = Convert.ToDouble(source);
  11.  
  12.     if (bytes >= Math.Pow(byteConversion, 3)) //GB Range
  13.     {
  14.         return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 3), 2), " GB");
  15.     }
  16.     else if (bytes >= Math.Pow(byteConversion, 2)) //MB Range
  17.     {
  18.         return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 2), 2), " MB");
  19.     }
  20.     else if (bytes >= byteConversion) //KB Range
  21.     {
  22.         return string.Concat(Math.Round(bytes / byteConversion, 2), " KB");
  23.     }
  24.     else //Bytes
  25.     {
  26.         return string.Concat(bytes, " Bytes");
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment