Mega Code Archive

 
Categories / C# / File Stream
 

Converts a number of bytes into a more easily read form

// Copyright 2008-2009 Mike Hurley // This program and associated libraries are licensed under the GNU LGPL 2.1 // See LICENSE.TXT in the root folder for the license. using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.IO; namespace DirectoryChunker {     /// <summary>     /// Misc. utility methods.     /// </summary>     public class Utility     {         private Utility() { }         /// <summary>         /// Converts a number of bytes into a more easily read form.         /// Ex. 1024 bytes returns &quot;1.00 KB&quot;         /// </summary>         /// <param name="bytes">Byte size to convert.</param>         /// <returns>String representation of bytes.</returns>         public static string GetFileSizeAsStringWithSuffix(ulong bytes)         {             string[] suffixArray = new string[] { "{0:N0} B", "{0:N2} KB", "{0:N2} MB", "{0:N2} GB", "{0:N2} TB", "{0:N2} PB" };             int suffixIndex = 0;             double size = (double)bytes;             while (suffixIndex < suffixArray.Length &&                 size >= 1024.0)             {                 suffixIndex++;                 size /= 1024.0;             }             return string.Format(suffixArray[suffixIndex], size);         }     } }