• Code
  • Tags
  • Users
  • Titles
  • Log in
  • Feedback
  • FAQ
Share Code
Welcome to ForkCan.com

ForkCan is all about sharing code in a social way.

Discuss, debate or argue with other devs about their or your own code.

Give other devs feedback or make a Fork (Make a better version of a shared code).

Rate the code, if you use the code mark it as used so others can see if the shared code is used by someone.

Help each other to be better devs and to be more productive.


Features not working yet:

Flag a post


QR Code

Tiny Url

http://4kcan.com/s/MjI1

Display number of bytes as a string given in kB, MB, GB etc

Convert number of bytes into a more "friendly" like string that display number of kB, MB or GB etc.

0
701 0 0 0 0 1

internal static class Extensions
{
	// Unit specifications
	private static string[][] byteUnits = new string[][]
	{
		new string[] { "bytes", "bytes" },
		new string[] { "kB", "kilobyte" },
		new string[] { "MB", "megabyte" },
		new string[] { "GB", "gigabyte" },
		new string[] { "TB", "terabyte" },
		new string[] { "PB", "petabyte" },
		new string[] { "EB", "exabyte" },
	};
	internal static string ToByteUnitString(this long byteCount, bool abbreviatedName = true)
	{
		int i = Convert.ToInt32(Math.Floor(Math.Log(byteCount, 2) / 10f));
		if (i == 0)
			return string.Format("{0} {1}", byteCount, (abbreviatedName) ? byteUnits[i][0] : byteUnits[i][1]);
		return string.Format("{0:F2} {1}", byteCount / Math.Pow(1024, i), (abbreviatedName) ? byteUnits[i][0] : byteUnits[i][1]);
	}
}

Example:

void Main()
{
	var sizeString = new DriveInfo("C").AvailableFreeSpace.ToByteUnitString();

	// test all units -- unit in abbreviated and normal
	foreach (int i in Enumerable.Range(0, 6))
	{
		Console.WriteLine(((long)Math.Pow(1024, i)).ToByteUnitString(true));
		Console.WriteLine(((long)Math.Pow(1024, i)).ToByteUnitString(false));
	}
}

Share: twitter | facebook   Action: used | fork | flag

bytes

Mark 'bytes' tag as 'like'

Mark 'bytes' tag as 'ignore'

c#

Mark 'c#' tag as 'like'

Mark 'c#' tag as 'ignore'


 @toha73 "Code Contributor"
716
August 02, 2010 2:35 PM
edited October 01, 2011 12:19 AM

Fork

 Display number of bytes as a string given in kB, MB, GB etc -  @toha73 Monday 02, 2010 2:35 PM


0 Feedback


You must log in before you can give any feedback


1 Discussion(s)

Newest Oldest
0

Suggest you have your string array as a static member in your class so it is initialized just once. 1024 should be a constant. The use of 4 should be sizes.Length-1.

link | flag  | Reply

 cellfish
10
Tuesday 10, 2010 7:41 PM


You must log in before you can post a comment

Squeed
Made by: Fredrik Normén 2010