converting bytes to an appropriate file size description


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



Copy this code and paste it in your HTML
  1. namespace Kyrathasoft.Conversions.GetFilesizeDescription {
  2.  
  3. using System;
  4.  
  5. public static class clsGetFilesizeDescription {
  6.  
  7. public static string getFilesizeDesc(double sizeInBytes) {
  8.  
  9. const double Terabyte = 1099511627776;
  10. const double Gigabyte = 1073741824;
  11. const double Megabyte = 1048576;
  12. const double Kilobyte = 1024;
  13.  
  14. string result = string.Empty;
  15. double the_size = 0;
  16. string units = string.Empty;
  17.  
  18. if (sizeInBytes >= Terabyte) {
  19. the_size = sizeInBytes / Terabyte;
  20. units = " Tb";
  21. }
  22. else {
  23. if (sizeInBytes >= Gigabyte) {
  24. the_size = sizeInBytes / Gigabyte;
  25. units = " Gb";
  26. }
  27. else {
  28. if (sizeInBytes >= Megabyte) {
  29. the_size = sizeInBytes / Megabyte;
  30. units = " Mb";
  31. }
  32. else {
  33. if (sizeInBytes >= Kilobyte) {
  34. the_size = sizeInBytes / Kilobyte;
  35. units = " Kb";
  36. }
  37. else {
  38. the_size = sizeInBytes;
  39. units = " bytes";
  40. }
  41. }
  42. }
  43. }
  44.  
  45. if (units != "bytes") {
  46. result = the_size.ToString("N3") + " " + units;
  47. }
  48. else {
  49. result = the_size.ToString() + " " + units;
  50. }
  51. return result;
  52. }
  53.  
  54. }
  55. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.