Get Memory Size String From Bytes - CSharp System

CSharp examples for System:String Format

Description

Get Memory Size String From Bytes

Demo Code


using System;/*from ww  w  .j  ava2  s. c  om*/

public class Main{
        public static string GetMemStringFromBytes(long bytes, int maxLength, bool space)
        {
            return GetMemStringFromBytes(bytes, space).PadLeft(maxLength, ' ');
        }
        public static string GetMemStringFromBytes(long bytes, int maxLength)
        {
            return GetMemStringFromBytes(bytes, false).PadLeft(maxLength, ' ');
        }
        public static string GetMemStringFromBytes(long bytes, bool space)
        {
            decimal num = bytes / 1024M;
            string str = "KB";
            while (num >= 1000M)
            {
                if (str == "KB")
                {
                    num /= 1024M;
                    str = "MB";
                }
                else
                {
                    if (str == "MB")
                    {
                        num /= 1024M;
                        str = "GB";
                        continue;
                    }
                    if (str == "GB")
                    {
                        num /= 1024M;
                        str = "TB";
                        continue;
                    }
                    if (str == "TB")
                    {
                        num /= 1024M;
                        str = "PB";
                        continue;
                    }
                    if (str == "PB")
                    {
                        num /= 1024M;
                        str = "XB";
                        continue;
                    }
                    if (str == "XB")
                    {
                        num /= 1024M;
                        str = "ZB";
                        continue;
                    }
                    if (str == "ZB")
                    {
                        num /= 1024M;
                        str = "YB";
                        continue;
                    }
                    if (str == "YB")
                    {
                        num /= 1024M;
                        str = "??";
                        continue;
                    }
                    num /= 1024M;
                }
            }
            return (num.ToString("N2") + (space ? (" " + str) : str));
        }
}

Related Tutorials