Loading ...

C#: Convert bytes to represntable string in KB, MB and GB format | CodeAsp.Net

C#: Convert bytes to represntable string in KB, MB and GB format

 /5
0 (0votes)

If youhave the bytes with you and want to convert to string in like 10KB, 10MB or 10GB the following code will help you:

        public static String BytesToString(double byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; // Longs run out around EB
            if (byteCount == 0)
            {
                return string.Format("0{0}", suf[0]);
            }
            double bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return string.Format("{0}{1}", (Math.Sign(byteCount) * num).ToString(), suf[place]);
        }

Usage:

BytesToString(100000);

Comments (no comments yet)

Top Posts