How to return KB, MB and GB from Bytes using a public function

前端 未结 6 1571
囚心锁ツ
囚心锁ツ 2021-02-10 01:49

I\'m writing a "function" that returns a file\'s size (in B, KB, MB, GB).

The VB.Net code always gets the size in bytes first, so when a file\'s size (in Bytes)

6条回答
  •  盖世英雄少女心
    2021-02-10 01:52

    this post helped me out when I was trying to sort this out Learning C#, I usually use VB. Anyway I thought I'd post my update in case anyone cares to use it. It is in VB as I have a library of useful Functions and Subs that I use to keep this stuff in, And I started it in VB and too lazy to change all that code. It works well for me, so I hope it helps someone out.

    Function ByteConv(Bytes As Double, Optional Style As Integer = 1) As String
    
        Dim count As Integer = 0
        Dim factor As Integer = 1024
        Dim Workingnum As Double = Bytes
        Dim Suffix() As String = {"Bytes", "Kb", "Mb", "Tb", "Pb", "Eb"} 'Dimention the string array upto Exobyte .. Cos why not?'
    
        If Style - 1 Then factor = 1000 Else factor = 1024  'This allows for Function to be used for Comms Calculations. I.e So it returns 100MB connection rather than 95.37'
    
        While Workingnum > factor And count < 5             'Basically keep dividing the Bytecount by the factor until the result reaches a whole number less that the factor itself'
            Workingnum = Workingnum / factor                ' '
            count = count + 1
        End While
        Return Workingnum.ToString("N") + Suffix(count)     ' Then return a string that includes the result and the applicable suffix.'
    End Function
    

提交回复
热议问题