Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Visual Basic
  4. Filesize Conversion

Filesize Conversion

Scheduled Pinned Locked Moved Visual Basic
csharphelp
22 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Dayekh

    Thank you all for your input. I have finally written a function to do exactly what I need to be done. Please look at the code below and benefit from it if you wish:

        Public Function BytesFormatting(ByVal Bytes As Integer) As String
    
            Dim FormattedFileSize As Double
    
            If Bytes < 1024 Then
                ''code to format fsize as KB
                Dim dblFormatted As Double
                dblFormatted = Bytes
                FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
    
            ElseIf (Bytes > 1024 And Bytes < 1048576) Then
                ''code to format fsize as KB
                Dim dblFormatted As Double
                dblFormatted = (Bytes + 1023) / 1024
                FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
    
            ElseIf Bytes > 1048576 Then
                ''code to format fsize as MB
                Dim dblFormatted As Double
                dblFormatted = (Bytes / 1024) / 1024
                FormattedFileSize = Format(dblFormatted, "###,###,###.00") + "MB"
            End If
    
            Return FormattedFileSize.ToString
        End Function
    
    T Offline
    T Offline
    The Man from U N C L E
    wrote on last edited by
    #10

    Hate to be the bearer of bad news but you have a typo in your first if chunk.

    Dayekh wrote:

    If Bytes < 1024 Then ''code to format fsize as KB Dim dblFormatted As Double dblFormatted = Bytes FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"

    Surely you mean bytes here rather than kilobytes, eg.

    If Bytes < 1024 Then
    ''code to format fsize as B (bytes)
    Dim dblFormatted As Double
    dblFormatted = Bytes
    FormattedFileSize = Format(dblFormatted, "###,###.00") + "B"

    If you have knowledge, let others light their candles at it. Margaret Fuller (1810 - 1850) [My Articles]  [My Website]

    D 1 Reply Last reply
    0
    • T The Man from U N C L E

      Hate to be the bearer of bad news but you have a typo in your first if chunk.

      Dayekh wrote:

      If Bytes < 1024 Then ''code to format fsize as KB Dim dblFormatted As Double dblFormatted = Bytes FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"

      Surely you mean bytes here rather than kilobytes, eg.

      If Bytes < 1024 Then
      ''code to format fsize as B (bytes)
      Dim dblFormatted As Double
      dblFormatted = Bytes
      FormattedFileSize = Format(dblFormatted, "###,###.00") + "B"

      If you have knowledge, let others light their candles at it. Margaret Fuller (1810 - 1850) [My Articles]  [My Website]

      D Offline
      D Offline
      Dayekh
      wrote on last edited by
      #11

      Not at all, that was intentional. However I should have been clearer. The reason that code block refers to formatting in KiloBytes is because I would like any file that is less than 1024 to be displayed as KB as well. For example a file that is 643 Bytes big will appear as 0.64KB Cheers.

      1 Reply Last reply
      0
      • D DaveAuld

        I was being overly simplistic to try and find out what exactly the problem is........i would hope that anybody who is working in IT knows the relationships between bits bytes k, m, g, t.....and on and on. but yes agree with your point, i.e. never show zero unless it is actually zero.

        Dave Don't forget to rate messages!
        Find Me On: Web|Facebook|Twitter|LinkedIn
        Waving? dave.m.auld[at]googlewave.com

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #12

        daveauld wrote:

        i would hope that anybody who is working in IT knows the relationships between bits bytes k, m, g, t.....and on and on.

        Never assume this. I once heard one of our IT help desk reps ask a colleague "What exactly is hexadecimal?".

        It's time for a new signature.

        S P 2 Replies Last reply
        0
        • L Lost User

          daveauld wrote:

          i would hope that anybody who is working in IT knows the relationships between bits bytes k, m, g, t.....and on and on.

          Never assume this. I once heard one of our IT help desk reps ask a colleague "What exactly is hexadecimal?".

          It's time for a new signature.

          S Offline
          S Offline
          scottgp
          wrote on last edited by
          #13

          I worked with a woman who was supposedly in IT for at least 10 years, who was previously an Oracle instructor, and asked me how to convert K to MB. Scary. Scott

          1 Reply Last reply
          0
          • D Dayekh

            Thank you all for your input. I have finally written a function to do exactly what I need to be done. Please look at the code below and benefit from it if you wish:

                Public Function BytesFormatting(ByVal Bytes As Integer) As String
            
                    Dim FormattedFileSize As Double
            
                    If Bytes < 1024 Then
                        ''code to format fsize as KB
                        Dim dblFormatted As Double
                        dblFormatted = Bytes
                        FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
            
                    ElseIf (Bytes > 1024 And Bytes < 1048576) Then
                        ''code to format fsize as KB
                        Dim dblFormatted As Double
                        dblFormatted = (Bytes + 1023) / 1024
                        FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
            
                    ElseIf Bytes > 1048576 Then
                        ''code to format fsize as MB
                        Dim dblFormatted As Double
                        dblFormatted = (Bytes / 1024) / 1024
                        FormattedFileSize = Format(dblFormatted, "###,###,###.00") + "MB"
                    End If
            
                    Return FormattedFileSize.ToString
                End Function
            
            R Offline
            R Offline
            riced
            wrote on last edited by
            #14

            What if file is exactly 1024 or 1048576 bytes? Not likely but not impossible, I can generate one of either size with ease. :)

            Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

            L 1 Reply Last reply
            0
            • R riced

              What if file is exactly 1024 or 1048576 bytes? Not likely but not impossible, I can generate one of either size with ease. :)

              Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #15

              right. and doesn't Dim FormattedFileSize As Double deserve some attention too? :)

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


              Prolific encyclopedia fixture proof-reader browser patron addict?
              We all depend on the beast below.


              R 1 Reply Last reply
              0
              • L Luc Pattyn

                right. and doesn't Dim FormattedFileSize As Double deserve some attention too? :)

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                Prolific encyclopedia fixture proof-reader browser patron addict?
                We all depend on the beast below.


                R Offline
                R Offline
                riced
                wrote on last edited by
                #16

                Yup. But I guess he has Option Strict Off either intentionally or by default. That allows it to compile. But there's even worse when you look at it more closely e.g. a file of 1023 bytes returns 1,023.00KB. :-D He did say it was working so I suppose he tested it. :laugh:

                Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

                L 1 Reply Last reply
                0
                • R riced

                  Yup. But I guess he has Option Strict Off either intentionally or by default. That allows it to compile. But there's even worse when you look at it more closely e.g. a file of 1023 bytes returns 1,023.00KB. :-D He did say it was working so I suppose he tested it. :laugh:

                  Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

                  L Offline
                  L Offline
                  Luc Pattyn
                  wrote on last edited by
                  #17

                  I have finally written a function to do exactly what I need to be done. Please look at the code below and benefit from it if you wish I think he meant: no need for me to test it, just publish and wait a while. Not sure it will still do what "needs to be done" when we are through... :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                  Prolific encyclopedia fixture proof-reader browser patron addict?
                  We all depend on the beast below.


                  1 Reply Last reply
                  0
                  • D Dayekh

                    Thank you all for your input. I have finally written a function to do exactly what I need to be done. Please look at the code below and benefit from it if you wish:

                        Public Function BytesFormatting(ByVal Bytes As Integer) As String
                    
                            Dim FormattedFileSize As Double
                    
                            If Bytes < 1024 Then
                                ''code to format fsize as KB
                                Dim dblFormatted As Double
                                dblFormatted = Bytes
                                FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
                    
                            ElseIf (Bytes > 1024 And Bytes < 1048576) Then
                                ''code to format fsize as KB
                                Dim dblFormatted As Double
                                dblFormatted = (Bytes + 1023) / 1024
                                FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
                    
                            ElseIf Bytes > 1048576 Then
                                ''code to format fsize as MB
                                Dim dblFormatted As Double
                                dblFormatted = (Bytes / 1024) / 1024
                                FormattedFileSize = Format(dblFormatted, "###,###,###.00") + "MB"
                            End If
                    
                            Return FormattedFileSize.ToString
                        End Function
                    
                    R Offline
                    R Offline
                    riced
                    wrote on last edited by
                    #18

                    I decide to benefit and wrote something that does work. :-D Try plugging yours into the Main and see what happens. :)

                    Module Module1
                    Sub Main()
                    Dim s As String = ""
                    Console.WriteLine("--- Kilobytes ---")
                    s = FormattedFileSize(1023)
                    Console.WriteLine("1023 > " & s)
                    s = FormattedFileSize(1024)
                    Console.WriteLine("1024 > " & s)
                    s = FormattedFileSize(1025)
                    Console.WriteLine("1025 > " & s)

                      Console.WriteLine("--- Megabytes ---")
                      s = FormattedFileSize(1048575)
                      Console.WriteLine("1048575 > " & s)
                      s = FormattedFileSize(1048576)
                      Console.WriteLine("1048576 > " & s)
                      s = FormattedFileSize(1048577)
                      Console.WriteLine("1048577 > " & s)
                      s = FormattedFileSize(1048576 \* 2)
                      Console.WriteLine("1048577 \* 2 > " & s)
                    
                      Console.WriteLine("--- Gigabytes ---")
                      s = FormattedFileSize(1048576 \* 1024)
                      Console.WriteLine("1048576 \* 1024 > " & s)
                    
                      Console.ReadLine()
                    

                    End Sub

                    Public Function FormattedFileSize(ByVal sizeInBytes As Long) As String
                    Dim suffix() As String = New String() {"", "KB", "MB", "GB", "XX"}
                    Dim retVal As String = "Oops"
                    Dim units As Double = sizeInBytes
                    Dim index As Integer = 0
                    Do
                    units = units / 1024.0
                    index += 1
                    Loop While units >= 1024.0

                      retVal = Format(units, "###,###,##0.000") + suffix(index)
                      Return retVal
                    

                    End Function

                    End Module

                    PS you just need to change the name of the function calls e.g. use s = BytesFormatting(1024)

                    Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

                    L 1 Reply Last reply
                    0
                    • D Dayekh

                      Thank you all for your input. I have finally written a function to do exactly what I need to be done. Please look at the code below and benefit from it if you wish:

                          Public Function BytesFormatting(ByVal Bytes As Integer) As String
                      
                              Dim FormattedFileSize As Double
                      
                              If Bytes < 1024 Then
                                  ''code to format fsize as KB
                                  Dim dblFormatted As Double
                                  dblFormatted = Bytes
                                  FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
                      
                              ElseIf (Bytes > 1024 And Bytes < 1048576) Then
                                  ''code to format fsize as KB
                                  Dim dblFormatted As Double
                                  dblFormatted = (Bytes + 1023) / 1024
                                  FormattedFileSize = Format(dblFormatted, "###,###.00") + "KB"
                      
                              ElseIf Bytes > 1048576 Then
                                  ''code to format fsize as MB
                                  Dim dblFormatted As Double
                                  dblFormatted = (Bytes / 1024) / 1024
                                  FormattedFileSize = Format(dblFormatted, "###,###,###.00") + "MB"
                              End If
                      
                              Return FormattedFileSize.ToString
                          End Function
                      
                      D Offline
                      D Offline
                      Dayekh
                      wrote on last edited by
                      #19

                      Thank you all for your input! I certainly was happy that this issue had a lot of interest. "i would hope that anybody who is working in IT knows the relationships between bits bytes k, m, g, t.....and on and on." -- knowing the relationship between bytes, KB, MB, etc.. was irrelevant as I was asking if there was a class/method that automatically did the conversions in VB.Net. And yes, I know the relationship between them :P "I think he meant: no need for me to test it, just publish and wait a while." -- Yea I'm sure all programmers are perfect testers of THEIR own code. I did some testing, but it obviously wasn't good enough. I suppose that's what learning is.. no? "What if file is exactly 1024 or 1048576 bytes?" -- Good point! I was swamped with work that I overlooked that fault. Thank you. "But there's even worse when you look at it more closely e.g. a file of 1023 bytes returns 1,023.00KB." -- Another good point. I need to address all eventualities more closely! "I decide to benefit and wrote something that does work." -- Thank you. I will work through that code. Thanks again all! This made my day.

                      1 Reply Last reply
                      0
                      • R riced

                        I decide to benefit and wrote something that does work. :-D Try plugging yours into the Main and see what happens. :)

                        Module Module1
                        Sub Main()
                        Dim s As String = ""
                        Console.WriteLine("--- Kilobytes ---")
                        s = FormattedFileSize(1023)
                        Console.WriteLine("1023 > " & s)
                        s = FormattedFileSize(1024)
                        Console.WriteLine("1024 > " & s)
                        s = FormattedFileSize(1025)
                        Console.WriteLine("1025 > " & s)

                          Console.WriteLine("--- Megabytes ---")
                          s = FormattedFileSize(1048575)
                          Console.WriteLine("1048575 > " & s)
                          s = FormattedFileSize(1048576)
                          Console.WriteLine("1048576 > " & s)
                          s = FormattedFileSize(1048577)
                          Console.WriteLine("1048577 > " & s)
                          s = FormattedFileSize(1048576 \* 2)
                          Console.WriteLine("1048577 \* 2 > " & s)
                        
                          Console.WriteLine("--- Gigabytes ---")
                          s = FormattedFileSize(1048576 \* 1024)
                          Console.WriteLine("1048576 \* 1024 > " & s)
                        
                          Console.ReadLine()
                        

                        End Sub

                        Public Function FormattedFileSize(ByVal sizeInBytes As Long) As String
                        Dim suffix() As String = New String() {"", "KB", "MB", "GB", "XX"}
                        Dim retVal As String = "Oops"
                        Dim units As Double = sizeInBytes
                        Dim index As Integer = 0
                        Do
                        units = units / 1024.0
                        index += 1
                        Loop While units >= 1024.0

                          retVal = Format(units, "###,###,##0.000") + suffix(index)
                          Return retVal
                        

                        End Function

                        End Module

                        PS you just need to change the name of the function calls e.g. use s = BytesFormatting(1024)

                        Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

                        L Offline
                        L Offline
                        Luc Pattyn
                        wrote on last edited by
                        #20

                        You have some IndexOutOfRange problems... As a little VB exercise, here an alternative, spanning a larger range of values; the result is slightly different, notation is float or integer as appropriate:

                        Private Sub Button1\_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                            Dim pow As Long = 1
                            For i = 0 To 63
                                Dim fraction As Long = pow \\ 32
                                If fraction < 1 Then fraction = 1
                                test(-pow)
                                test(pow - fraction)
                                test(pow)
                                test(pow + fraction)
                                If pow >= &H4000000000000000 Then Exit For
                                pow = 2 \* pow
                            Next
                        End Sub
                        
                        Public Sub test(ByVal value As Long)
                            Dim s As String
                            s = FormattedFileSize(value)
                            Console.WriteLine(value.ToString().PadLeft(20) & " = " & value.ToString("X16") & " = " & s & "B")
                        End Sub
                        
                        Public Function FormattedFileSize(ByVal sizeInBytes As Long) As String
                            Dim negative As Boolean = False
                            Dim result As String
                            Dim value As Long = sizeInBytes
                            Dim remainder As Long = 0
                            Dim suffixIndex As Integer
                            If value < 0 Then
                                negative = True
                                value = -value
                            End If
                            For suffixIndex = 0 To 20
                                If value <= 1023 Then Exit For
                                remainder = value Mod 1024
                                value = value \\ 1024
                            Next
                            If remainder > 0 Then
                                Dim d As Double = value + remainder / 1024
                                result = d.ToString("F3")
                            Else
                                result = value.ToString()
                            End If
                            If suffixIndex > 0 Then result = result & " KMGTPEZY"(suffixIndex)
                            If negative Then result = "-" & result
                            Return result
                        End Function
                        

                        Homework: find and fix the value(s) that still fail. :)

                        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                        Prolific encyclopedia fixture proof-reader browser patron addict?
                        We all depend on the beast below.


                        R 1 Reply Last reply
                        0
                        • L Luc Pattyn

                          You have some IndexOutOfRange problems... As a little VB exercise, here an alternative, spanning a larger range of values; the result is slightly different, notation is float or integer as appropriate:

                          Private Sub Button1\_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                              Dim pow As Long = 1
                              For i = 0 To 63
                                  Dim fraction As Long = pow \\ 32
                                  If fraction < 1 Then fraction = 1
                                  test(-pow)
                                  test(pow - fraction)
                                  test(pow)
                                  test(pow + fraction)
                                  If pow >= &H4000000000000000 Then Exit For
                                  pow = 2 \* pow
                              Next
                          End Sub
                          
                          Public Sub test(ByVal value As Long)
                              Dim s As String
                              s = FormattedFileSize(value)
                              Console.WriteLine(value.ToString().PadLeft(20) & " = " & value.ToString("X16") & " = " & s & "B")
                          End Sub
                          
                          Public Function FormattedFileSize(ByVal sizeInBytes As Long) As String
                              Dim negative As Boolean = False
                              Dim result As String
                              Dim value As Long = sizeInBytes
                              Dim remainder As Long = 0
                              Dim suffixIndex As Integer
                              If value < 0 Then
                                  negative = True
                                  value = -value
                              End If
                              For suffixIndex = 0 To 20
                                  If value <= 1023 Then Exit For
                                  remainder = value Mod 1024
                                  value = value \\ 1024
                              Next
                              If remainder > 0 Then
                                  Dim d As Double = value + remainder / 1024
                                  result = d.ToString("F3")
                              Else
                                  result = value.ToString()
                              End If
                              If suffixIndex > 0 Then result = result & " KMGTPEZY"(suffixIndex)
                              If negative Then result = "-" & result
                              Return result
                          End Function
                          

                          Homework: find and fix the value(s) that still fail. :)

                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                          Prolific encyclopedia fixture proof-reader browser patron addict?
                          We all depend on the beast below.


                          R Offline
                          R Offline
                          riced
                          wrote on last edited by
                          #21

                          I knew it would error for extremely large sizes and failed on negatives so here's a fix. (Not sure the negatives a right.)

                          Public Function FormattedFileSize(ByVal sizeInBytes As Long) As String
                          Dim suffix() As String = New String() {"Oops", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "XX"}
                          Dim units As Double = Math.Abs(sizeInBytes) 'Fudge to deal with negatives. Should it error with neg file size?
                          Dim index As Integer = 0

                            Do
                               units = units / 1024.0
                               index += 1
                            Loop While units >= 1024.0
                          
                            Return Format(units, "###,###,##0.000") + suffix(index)
                          

                          End Function

                          I've not done homework for years. :)

                          Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

                          1 Reply Last reply
                          0
                          • L Lost User

                            daveauld wrote:

                            i would hope that anybody who is working in IT knows the relationships between bits bytes k, m, g, t.....and on and on.

                            Never assume this. I once heard one of our IT help desk reps ask a colleague "What exactly is hexadecimal?".

                            It's time for a new signature.

                            P Offline
                            P Offline
                            Paul Conrad
                            wrote on last edited by
                            #22

                            Richard MacCutchan wrote:

                            once heard one of our IT help desk reps ask a colleague "What exactly is hexadecimal?"

                            :omg:

                            "The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon "Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups