Return to Snippet

Revision: 40362
at January 31, 2011 18:25 by Mike343


Initial Code
public static class FileExtension
	{
		private const double Kb = 1024;
		private const double Mb = 1024 * Kb;
		private const double Gb = 1024 * Mb;
		private const double Tb = 1024 * Gb;

		/// <summary>
		/// Returns a readable file size from the specified value.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public string AsReadableSize(this long value)
		{
			return AsReadableSize(Convert.ToInt32(value));
		}

		/// <summary>
		/// Returns a readable file size from the specified value.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		publicstring AsReadableSize(this int value)
		{
			if (value < Kb)
			{
				return string.Format(CultureInfo.InvariantCulture, "{0} Bytes", value);
			}

			if (value < Mb)
			{
				return string.Format(CultureInfo.InvariantCulture, "{0} KB", Math.Round(value / Kb, 2));
			}

			if (value < Gb)
			{
				return string.Format(CultureInfo.InvariantCulture, "{0} MB", Math.Round(value / Mb, 2));
			}

			return value < Tb 
				? string.Format(CultureInfo.InvariantCulture, "{0} GB", Math.Round(value / Gb, 2)) 
				: string.Format(CultureInfo.InvariantCulture, "{0} TB", Math.Round(value / Tb, 2));
		}
	}

Initial URL

                                

Initial Description

                                

Initial Title
Convert file size represented as byes to a readable value.

Initial Tags

                                

Initial Language
C#