UAD7 – File size, nearest unit mb,kb,gb.

Okay, so Util-a-day was a bit optimistic! Here’s the next one, simple function to convert a file size in a user friendly description. It converts the size to the nearest kb, mb or gb.

public static String ConvertBytes(double bytes){
	String FORMAT = "{0:N2}";
	if (bytes > 1073741824)
		return String.Format(FORMAT, (bytes / 1024 / 1024 / 1024)) + " GB";
	else if (bytes > 1048576)
		return String.Format(FORMAT, (bytes / 1024 / 1024)) + " MB";
	else if (bytes >= 1024)
		return String.Format(FORMAT, (bytes / 1024)) + " KB";
	else
		return bytes + " Bytes";
}

Leave a Reply

Your email address will not be published. Required fields are marked *