FormatAsFileLength

using System; using System.Web; using System.Web.Mvc; public static class MyExtensionMethods { // Sorry. I'm terrible to choose variable names... private static readonly string[] FileUnits = new string[] { "bytes", "KB", "MB", "GB", "TB" }; // As you can see... private const int FileUnitDivider = 1024; public static string FormatAsFileLength(this long? length, string unavailableValue = "(unavailable)") { if (!length.HasValue) { return unavailableValue; } else { // Starts with the source length. double currentValue = length.Value; // This index will be used to get the unit from the 'FileUnits' field. int currentUnit = 0; while ((currentValue > MyExtensionMethods.FileUnitDivider) && (currentUnit < MyExtensionMethods.FileUnits.Length)) { // While the 'currentValue' can be divided by 'FileUnitDivider' AND there's a highest unit, divide the value and increments the unit index. currentValue = currentValue / MyExtensionMethods.FileUnitDivider; currentUnit++; } // Get the unit from the index. string unit = MyExtensionMethods.FileUnits[currentUnit]; // Returns the formatted value. return string.Format("{0:N} {1}", currentValue, unit); } } }
Formats some long value as a file length unit.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.