uwekeim icon

Convert file sizes back and forth between human readable

uwekeim | PRO | 05/19/13 05:49:26 AM UTC | 0 ⭐ | 920 👁️ | Never ⏰ | []
C# |

2.68 KB

|

None

|

0 👍

/

0 👎

public static class SizeTranslationHelper
{
    /// <summary>
    /// Converts bytes to human-readable, e.g. "12.5GB".
    /// </summary>
    public static string MakeLazy(ulong byteCount)
    {
        string[] suf = { @"B", @"KB", @"MB", @"GB", @"TB", @"PB", @"EB" }; //Longs run out around EB
        if (byteCount == 0)
            return "0" + suf[0];
        var bytes = (ulong)Math.Abs((decimal)byteCount);
        var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024ul)));
        var num = Math.Round(bytes / Math.Pow(1024ul, place), 1);
        return (Math.Sign((decimal)byteCount) * num).ToString(CultureInfo.InvariantCulture) + suf[place];
    }
 
    /// <summary>
    /// Converts human-readable, e.g. "12.5GB", to bytes.
    /// </summary>
    public static ulong TranslateLazySize(string sizeLazy)
    {
        sizeLazy = sizeLazy.ToLowerInvariant();
 
        ulong result = 0;
        if (tryParse(ref result, sizeLazy, @"b", 1ul))
        {
            return result;
        }
        else if (tryParse(ref result, sizeLazy, @"kb", 1024ul))
        {
            return result;
        }
        else if (tryParse(ref result, sizeLazy, @"mb", 1024ul * 1024ul))
        {
            return result;
        }
        else if (tryParse(ref result, sizeLazy, @"gb", 1024ul * 1024ul * 1024ul))
        {
            return result;
        }
        else if (tryParse(ref result, sizeLazy, @"tb", 1024ul * 1024ul * 1024ul * 1024ul))
        {
            return result;
        }
        else if (tryParse(ref result, sizeLazy, @"pb", 1024ul * 1024ul * 1024ul * 1024ul * 1024ul))
        {
            return result;
        }
        else if (tryParse(ref result, sizeLazy, @"eb", 1024ul * 1024ul * 1024ul * 1024ul * 1024ul * 1024ul))
        {
            return result;
        }
        else
        {
            decimal r;
            if (decimal.TryParse(sizeLazy, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out r))
            {
                return (ulong)r;
            }
            else
            {
                throw new Exception(string.Format(@"Cannot parse '{0}' to number.", sizeLazy));
            }
        }
    }
 
    private static bool tryParse(ref ulong result, string sizeLazy, string suffix, ulong factor)
    {
        decimal r;
        if (
            sizeLazy.EndsWith(suffix) &&
            decimal.TryParse(sizeLazy.Substring(0, sizeLazy.Length - suffix.Length), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out r))
        {
            result = (ulong)(r * factor);
            return true;
        }
        else
        {
            return false;
        }
    }
}

Comments