Does .Net Provide an Easy Way Convert Bytes to Kb, Mb, Gb, etc.

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is a fairly concise way to do this:

static readonly string[] SizeSuffixes = 
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }
if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

// mag is 0 for bytes, 1 for KB, 2, for MB, etc.
int mag = (int)Math.Log(value, 1024);

// 1L << (mag * 10) == 2 ^ (10 * mag)
// [i.e. the number of bytes in the unit corresponding to mag]
decimal adjustedSize = (decimal)value / (1L << (mag * 10));

// make adjustment when the value is large enough that
// it would round up to 1000 or more
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}

return string.Format("{0:n" + decimalPlaces + "} {1}",
adjustedSize,
SizeSuffixes[mag]);
}

And here's the original implementation I suggested, which may be marginally slower, but a bit easier to follow:

static readonly string[] SizeSuffixes = 
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }

int i = 0;
decimal dValue = (decimal)value;
while (Math.Round(dValue, decimalPlaces) >= 1000)
{
dValue /= 1024;
i++;
}

return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));

One thing to bear in mind - in SI notation, "kilo" usually uses a lowercase k while all of the larger units use a capital letter. Windows uses KB, MB, GB, so I have used KB above, but you may consider kB instead.

How can I convert bytes available to bytes available in KB, MB, GB etc?

I have found a very Informative Blog Regarding this :

https://askgif.com/blog/143/how-to-convert-given-bytes-in-kb-mb-gb-etc/ (Courtesy: https://askgif.com/)

if you are calculating total bytes then you can use the following function to find out the respective total bytes in KB, MB, GB, TB etc.

static String BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suf[place];
}

Hope this will help you.

How do I get a human-readable file size in bytes abbreviation using .NET?

This may not the most efficient or optimized way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
order++;
len = len/1024;
}

// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);

How to correctly convert filesize in bytes into mega or gigabytes?

1024 is correct for usage in programs.

The reason you may be having differences is likely due to differences in what driveinfo reports as "available space" and what windows considers available space.

Note that only drive manufacturers use 1,000. Within windows and most programs the correct scaling is 1024.

Also, while your compiler should optimize this anyway, this calculation can be done by merely shifting the bits by 10 for each magnitude:

KB = B >> 10

MB = KB >> 10 = B >> 20

GB = MB >> 10 = KB >> 20 = B >> 30

Although for readability I expect successive division by 1024 is clearer.

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

I would use a select case for it and not a if.

And always start with the biggest size." i stopped at TB but of Corse you can add more if you need ..."

I changed Dim TheSize As Integer to "Dim TheSize As ULong " otherwise big numbers don't work.

Also make a dim "Dim DoubleBytes As Double" you will use it in the select case.

First you compare the bytes you have with a case , lets say mb "Case 1048576 To 1073741823"

So if this is the case convert TheSize to a double "DoubleBytes = CDbl(TheSize / 1048576) 'MB
"

Then in the return you use FormatNumber to set the number you want to show behind the . "the nuber 2 is to set it to 2 behind the . like 28.11 , change it to 0 and it will return 28" also because you know it mb you wil add & mb to the return.

"Return FormatNumber(DoubleBytes, 2) & " MB"
"

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

I made a dll for it.

Then I can import it to my project and I can call it whenever I need to change a byte number to something else "like mb etc"

FormatBytes(GetHDSizeF) "GetHDSizeF is the number of bytes"

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

And if you don't want to make a dll you can use it like a normal function like this.

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

How do I convert the database size from mega bytes to bytes or vice-versa?

Bytes to Megabytes = Bytes / (1024 * 1024)
Megabytes to Bytes = Megabytes * (1024 * 1024.0)

Be sure to account for integer division, thus the 1024.0 so a floating point number is used.

convert a decimal from bytes to mb in mvc from a database

The "pure" way would be to add that to the model:

public Nullable<decimal> extensionattribute9InMB 
{
get {return extensionattribute9 / 1024m;}
}

And then choose which property you wanted to display in the view. The hacky way would be to do that calculation directly in the view.

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is a fairly concise way to do this:

static readonly string[] SizeSuffixes = 
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }
if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

// mag is 0 for bytes, 1 for KB, 2, for MB, etc.
int mag = (int)Math.Log(value, 1024);

// 1L << (mag * 10) == 2 ^ (10 * mag)
// [i.e. the number of bytes in the unit corresponding to mag]
decimal adjustedSize = (decimal)value / (1L << (mag * 10));

// make adjustment when the value is large enough that
// it would round up to 1000 or more
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}

return string.Format("{0:n" + decimalPlaces + "} {1}",
adjustedSize,
SizeSuffixes[mag]);
}

And here's the original implementation I suggested, which may be marginally slower, but a bit easier to follow:

static readonly string[] SizeSuffixes = 
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }

int i = 0;
decimal dValue = (decimal)value;
while (Math.Round(dValue, decimalPlaces) >= 1000)
{
dValue /= 1024;
i++;
}

return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));

One thing to bear in mind - in SI notation, "kilo" usually uses a lowercase k while all of the larger units use a capital letter. Windows uses KB, MB, GB, so I have used KB above, but you may consider kB instead.

bytes to human readable string

There is always a little confusion about how to display bytes. Your code is correct if the result is what you are trying to achieve.

What you showed from Google is a decimal representation. So just as you say 1000m = 1km, you can say 1000byte = 1kB.

On the other hand, there is the binary representation where 1k = 2^10 = 1024. These representations are called kibiBytes, Gibibytes etc.

Which representation you choose is up to you or the requirements of your customers. Just make obvious which you use to avoid confusion.



Related Topics



Leave a reply



Submit