locked
Format filesize in kB or MB RRS feed

  • Question

  • User-1457962578 posted
    Hello, When I have read a file with x.xxx.xxx.xxx bytes it is sometimes handy to show it in an diverent format than bytes. Is there a handy way to do this? Or is there a function for it? When it is a big file I want to see a MB size and when it is a lower file size then I want to see a kB size for example. Thanks!
    Friday, August 8, 2003 2:41 PM

All replies

  • User553272958 posted
    There isn't anything built in that I know of but it's really easy to accomplish this. I normally use something like this: if (fsize < 1024) // code to format fsize as bytes else if ((fsize > 1024) && (fsize < 1048576)) // code to format fsize as KB else if (fsize > 1048576) // code to format fsize as MB If there is something built in to do this, I would like to know about it too.
    Friday, August 8, 2003 3:09 PM
  • User645477409 posted
    Hi, A kB is 1024 bytes, and a MB is 1024 kB. Do the math... Hope this helps.
    Friday, August 8, 2003 3:14 PM
  • User-1430188240 posted
    You can use this piece of C# code to do this: using System; class Test { public static void Main(string[]args) { Console.WriteLine(GetSize(int.Parse(args[0]))); } public static string GetSize(long size) { double s = size; string[] format = new string[] {"{0} bytes", "{0} MB", "{0} GB", "{0} TB", "{0} PB", "{0} EB"}; int i = 0; while (i < format.Length && s >= 1024) { s = (int) (100 * s / 1024) / 100.0; i++; } return string.Format(format[i],s); } }
    Friday, August 8, 2003 4:21 PM
  • User-1772065905 posted

    I use to same code. 

    Public Function BytesToMegabytes(Bytes As Double) As Double
       'This function gives an estimate to two decimal
       'places.  For a more precise answer, format to
       'more decimal places or just return dblAns
     
      Dim dblAns As Double
      dblAns = (Bytes / 1024) / 1024
      BytesToMegabytes = Format(dblAns, "###,###,##0.00")
     
    End Function

    Wednesday, July 30, 2008 8:52 AM
  • User1505363701 posted

    Hi thanks alperdotnet, it works very well...

    Wednesday, June 15, 2011 4:43 PM
  • User-1251713904 posted

    Hey BDESMET, good code.  But I think you are missing "{0} KB", in your format string array.  So that line should probably be..

    string[] format = new string[] { "{0} bytes", "{0} KB", "{0} MB", "{0} GB", "{0} TB", "{0} PB", "{0} EB" };
    Wednesday, August 10, 2011 10:41 AM