Convert file size represented as byes to a readable value.


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public static class FileExtension
  2. {
  3. private const double Kb = 1024;
  4. private const double Mb = 1024 * Kb;
  5. private const double Gb = 1024 * Mb;
  6. private const double Tb = 1024 * Gb;
  7.  
  8. /// <summary>
  9. /// Returns a readable file size from the specified value.
  10. /// </summary>
  11. /// <param name="value">The value.</param>
  12. /// <returns></returns>
  13. public string AsReadableSize(this long value)
  14. {
  15. return AsReadableSize(Convert.ToInt32(value));
  16. }
  17.  
  18. /// <summary>
  19. /// Returns a readable file size from the specified value.
  20. /// </summary>
  21. /// <param name="value">The value.</param>
  22. /// <returns></returns>
  23. publicstring AsReadableSize(this int value)
  24. {
  25. if (value < Kb)
  26. {
  27. return string.Format(CultureInfo.InvariantCulture, "{0} Bytes", value);
  28. }
  29.  
  30. if (value < Mb)
  31. {
  32. return string.Format(CultureInfo.InvariantCulture, "{0} KB", Math.Round(value / Kb, 2));
  33. }
  34.  
  35. if (value < Gb)
  36. {
  37. return string.Format(CultureInfo.InvariantCulture, "{0} MB", Math.Round(value / Mb, 2));
  38. }
  39.  
  40. return value < Tb
  41. ? string.Format(CultureInfo.InvariantCulture, "{0} GB", Math.Round(value / Gb, 2))
  42. : string.Format(CultureInfo.InvariantCulture, "{0} TB", Math.Round(value / Tb, 2));
  43. }
  44. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.