如何使用公共函数从字节返回KB,MB和GB

时间:2014-12-08 21:22:36

标签: vb.net visual-studio-2010 .net-4.0

我正在写一个"功能"返回文件的大小(B,KB,MB,GB)。

VB.Net代码总是首先以字节为单位获取大小,因此当文件的大小(以字节为单位)小于100时,如果其>>则返回B. 1000然后我将它除以1000并返回KB。但是当它应该是MB时,我尝试除以1000000,它返回的大小总是比它应该的大2 MB!

有人可以告诉我我做错了什么!!

实施例

我的文件大小是(15,570,550字节)..是...(14.8 MB)

因此,当我通过此函数运行它时,它返回16MB!

守则

Public Function GetFileSize(ByVal TheFile As String, _
                            Optional ByVal ShowSizeType As Boolean = False) As String
    If TheFile.Length = 0 Then Return ""
    If Not System.IO.File.Exists(TheFile) Then Return ""
    '---
    Dim TheSize As Integer = My.Computer.FileSystem.GetFileInfo(TheFile).Length
    Dim SizeType As String = ""
    '---
    If TheSize < 1000 Then
        SizeType = "B"
    Else
        If TheSize < 1000000000 Then
            If TheSize < 1000000 Then
                SizeType = "KB"
                TheSize = TheSize / 1000
            Else
                SizeType = "MB"
                TheSize = TheSize / 1000000
            End If
        Else
            SizeType = "GB"

        End If
    End If
    '---
    If ShowSizeType = True Then
        Return TheSize & SizeType
    Else
        Return TheSize
    End If
End Function

6 个答案:

答案 0 :(得分:8)

我会使用一个选择案例,而不是if。
始终以最大尺寸开始。&#34;我停在结核病但是科西嘉你可以增加更多,如果你需要...&#34;

我将Dim TheSize As Integer改为&#34; Dim TheSize As ULong&#34;否则大数字不会工作。

同时制作昏暗的&#34; Dim DoubleBytes As Double&#34;你将在选择的情况下使用它。

首先你比较一下你拥有的字节数,比如mb&#34; Case 1048576 To 1073741823&#34;
因此,如果是这种情况,请将TheSize转换为double&#34; DoubleBytes = CDbl(TheSize / 1048576)&#39; MB &#34;

然后在返回中使用FormatNumber设置要在后面显示的数字。 &#34; nuber 2将其设置为2。比如28.11,将其改为0,它将返回28&#34;也因为你知道它,你会添加&amp;返回。
&#34;返回FormatNumber(DoubleBytes,2)&amp; &#34; MB&#34; &#34;

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    MsgBox(GetFileSize("E:\Software\TeamSpeak3-Client-win64-3.0.14.exe"))
End Sub

Dim DoubleBytes As Double

Public Function GetFileSize(ByVal TheFile As String) As String
    If TheFile.Length = 0 Then Return ""
    If Not System.IO.File.Exists(TheFile) Then Return ""
    '---
    Dim TheSize As ULong = My.Computer.FileSystem.GetFileInfo(TheFile).Length
    Dim SizeType As String = ""
    '---

    Try
        Select Case TheSize
            Case Is >= 1099511627776
                DoubleBytes = CDbl(TheSize / 1099511627776) 'TB
                Return FormatNumber(DoubleBytes, 2) & " TB"
            Case 1073741824 To 1099511627775
                DoubleBytes = CDbl(TheSize / 1073741824) 'GB
                Return FormatNumber(DoubleBytes, 2) & " GB"
            Case 1048576 To 1073741823
                DoubleBytes = CDbl(TheSize / 1048576) 'MB
                Return FormatNumber(DoubleBytes, 2) & " MB"
            Case 1024 To 1048575
                DoubleBytes = CDbl(TheSize / 1024) 'KB
                Return FormatNumber(DoubleBytes, 2) & " KB"
            Case 0 To 1023
                DoubleBytes = TheSize ' bytes
                Return FormatNumber(DoubleBytes, 2) & " bytes"
            Case Else
                Return ""
        End Select
    Catch
        Return ""
    End Try
End Function

我为它做了一个dll 然后我可以将它导入到我的项目中,每当我需要将字节数更改为其他内容时我都可以调用它#34;如mb等&#34;
FormatBytes(GetHDSizeF)&#34; GetHDSizeF是字节数&#34;

Dim DoubleBytes As Double
Default Public Property FormatBytes(ByVal BytesCaller As ULong) As String
    Get
        Try
            Select Case BytesCaller
                Case Is >= 1099511627776
                    DoubleBytes = CDbl(BytesCaller / 1099511627776) 'TB
                    Return FormatNumber(DoubleBytes, 2) & " TB"
                Case 1073741824 To 1099511627775
                    DoubleBytes = CDbl(BytesCaller / 1073741824) 'GB
                    Return FormatNumber(DoubleBytes, 2) & " GB"
                Case 1048576 To 1073741823
                    DoubleBytes = CDbl(BytesCaller / 1048576) 'MB
                    Return FormatNumber(DoubleBytes, 2) & " MB"
                Case 1024 To 1048575
                    DoubleBytes = CDbl(BytesCaller / 1024) 'KB
                    Return FormatNumber(DoubleBytes, 2) & " KB"
                Case 0 To 1023
                    DoubleBytes = BytesCaller ' bytes
                    Return FormatNumber(DoubleBytes, 2) & " bytes"
                Case Else
                    Return ""
            End Select
        Catch
            Return ""
        End Try
    End Get
    Set(value As String)

    End Set
End Property

如果你不想制作一个dll,你可以像使用这样的普通函数一样使用它。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    MsgBox(FormatBytes(2000))
End Sub

Dim DoubleBytes As Double
Public Function FormatBytes(ByVal BytesCaller As ULong) As String

    Try
        Select Case BytesCaller
            Case Is >= 1099511627776
                DoubleBytes = CDbl(BytesCaller / 1099511627776) 'TB
                Return FormatNumber(DoubleBytes, 2) & " TB"
            Case 1073741824 To 1099511627775
                DoubleBytes = CDbl(BytesCaller / 1073741824) 'GB
                Return FormatNumber(DoubleBytes, 2) & " GB"
            Case 1048576 To 1073741823
                DoubleBytes = CDbl(BytesCaller / 1048576) 'MB
                Return FormatNumber(DoubleBytes, 2) & " MB"
            Case 1024 To 1048575
                DoubleBytes = CDbl(BytesCaller / 1024) 'KB
                Return FormatNumber(DoubleBytes, 2) & " KB"
            Case 0 To 1023
                DoubleBytes = BytesCaller ' bytes
                Return FormatNumber(DoubleBytes, 2) & " bytes"
            Case Else
                Return ""
        End Select
    Catch
        Return ""
    End Try

End Function

答案 1 :(得分:4)

您需要除以1024而不是1000. 1 KB不是1000字节,它是1024字节。 1 MB不是1000 KB,它是1024 KB,依此类推。

这是一个很好的网站来解释所有这些:http://pc.net/helpcenter/answers/why_1024_bytes

答案 2 :(得分:4)

以下是我的操作方法,下面是我在Microsoft Access中使用的VBA函数,可以轻松转换为VB或VBScript等。

Public Function FormatFileSize(ByVal lngFileSize As Long) As String

  Dim x      As Integer:      x = 0
  Dim Suffix As String:  Suffix = ""
  Dim Result As Single:  Result = lngFileSize

  Do Until Int(Result) < 1000
     x = x + 1
     Result = Result / 1024
  Loop

  Result = Round(Result, 2)

  Select Case x
         Case 0
              Suffix = "Bytes"
         Case 1 'KiloBytes
              Suffix = "KB"
         Case 2 'MegaBytes
              Suffix = "MB"
         Case 3 'GigaBytes
              Suffix = "GB"
         Case 4 'TeraBytes
              Suffix = "TB"
         Case 5 'PetaBytes
              Suffix = "PB"
         Case 6 'ExaBytes
              Suffix = "EB"
         Case 7 'ZettaBytes
              Suffix = "ZB"
         Case 8 'YottaBytes
              Suffix = "YB"
         Case Else
              Suffix = "Too big to compute :)"
  End Select

  FormatFileSize = Format(Result, "#,##0.00") & " " & Suffix

End Function 'FormatFileSize

答案 3 :(得分:2)

这篇文章帮我解决了当我试图解决这个问题时学习C#,我通常使用VB。无论如何,我想我会发布我的更新,以防有人关心使用它。 它是在VB中,因为我有一个有用的函数库和子函数库,我用它来保存这些东西,而我在VB中启动它并且懒得改变所有代码。它适合我,所以我希望它可以帮助别人。

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

答案 4 :(得分:1)

这是我在评论中的意思的一个例子:

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

<强>结果:

File Sizes example

答案 5 :(得分:0)

  Public Function GetDirSize(RootFolder As String) As Long
        Dim FolderInfo = New IO.DirectoryInfo(RootFolder)
        For Each File In FolderInfo.GetFiles : TotalSize += File.Length
        Next
        For Each SubFolderInfo In FolderInfo.GetDirectories : GetDirSize(SubFolderInfo.FullName)
        Next
        Return TotalSize
    End Function

    Public Sub GetfilesizeFromDirectory()
        Dim path As String
        path = "D:"
        TotalSize = 0 'Reset the counter
        Dim TheSize As Long = GetDirSize(path)
        ' TextBox1.Text = (FormatNumber(TheSize / 1024 / 1024 / 1) & vbCr & "MB")
    End Sub