public string FormatBytes(long bytes) { const int scale = 1024; string[] orders = new string[] { "GB", "MB", "KB", "Bytes" }; long max = (long)Math.Pow(scale, orders.Length - 1); foreach (string order in orders) { if ( bytes > max ) return string.Format("{0:##.##} {1}", decimal.Divide( bytes, max ), order); max /= scale; } return "0 Bytes"; }
개선전 코드
public string FormatBytes(int Bytes) { string filesize; if (Bytes >= 1073741824) { decimal size = decimal.Divide(Bytes, 1073741824); filesize = string.Format("{0:##.##} GB", size); } else if (Bytes >= 1048576) { decimal size = decimal.Divide(Bytes, 1048576); filesize = string.Format("{0:##.##} MB", size); } else if (Bytes >= 1024) { decimal size = decimal.Divide(Bytes, 1024); filesize = string.Format("{0:##.##} KB", size); } else if (Bytes > 0 & Bytes < 1024) { decimal size = Bytes; filesize = string.Format("{0:##.##} Bytes", size); } else { filesize = "0 Bytes"; } return filesize; }