1. Herfried K. Wagner’s VB.Any
  2. .NET
  3. Häufig gestellte Fragen

Formatieren einer Byteanzahl in einen formatierten String mit Einheit

Formatieren einer Byteanzahl in einen formatierten String mit Einheit
<URL:https://dotnet.currifex.org/dotnet/faqs/formatbytes/de/>
----------------------------------------------------------------------------

Formatting a number of bytes to a string with unit

'StrFormatByteSize' can be used to format a number of bytes as a "human
readable" string.  For example, 100,000,000 will be formatted as "95,3 MB"
on a 'de-DE' system:

\\\
Private Declare Auto Function StrFormatByteSize Lib "shlwapi.dll" ( _
    ByVal qdw As UInt64, _
    ByVal szBuf As String, _
    ByVal uiBufSize As Int32 _
) As IntPtr

Private Function FormatBytes(ByVal Bytes As UInt64) As String
    Dim s As String = Space(256)
    If StrFormatByteSize(Bytes, s, s.Length).Equals(IntPtr.Zero) Then
        Throw New Exception("Conversion failed.")
    Else
        Return Left(s, InStr(s, ControlChars.NullChar) - 1)
    End If
End Function
///

Usage:

\\\
MsgBox(FormatBytes(Convert.ToUInt64("100000000")))
MsgBox(FormatBytes(Convert.ToUInt64("100000000000000")))
///