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

前端 未结 6 1553
囚心锁ツ
囚心锁ツ 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 02:04

    This is an example of what I meant in my comment:

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim CalculatedSize As Decimal
            Dim TheSize As Long = Long.Parse(My.Computer.FileSystem.GetFileInfo(OpenFileDialog1.FileName).Length)
            Dim SizeType As String = "B"
    
            If TheSize < 1024 Then
                CalculatedSize = TheSize
    
            ElseIf TheSize > 1024 AndAlso TheSize < (1024 ^ 2) Then 'KB
                CalculatedSize = Math.Round((TheSize / 1024), 2)
                SizeType = "KB"
    
            ElseIf TheSize > (1024 ^ 2) AndAlso TheSize < (1024 ^ 3) Then 'MB
                CalculatedSize = Math.Round((TheSize / (1024 ^ 2)), 2)
                SizeType = "MB"
    
            ElseIf TheSize > (1024 ^ 3) AndAlso TheSize < (1024 ^ 4) Then 'GB
                CalculatedSize = Math.Round((TheSize / (1024 ^ 3)), 2)
                SizeType = "GB"
    
            ElseIf TheSize > (1024 ^ 4) Then 'TB
                CalculatedSize = Math.Round((TheSize / (1024 ^ 4)), 2)
                SizeType = "TB"
    
            End If
    
            MessageBox.Show("File size is: " & CalculatedSize.ToString & " " & SizeType, "File size", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    

    Result:

    File Sizes example

提交回复
热议问题