Mega Code Archive

 
Categories / C# / File Stream
 

Returns a human-readable version of the file size (original is in bytes)

#region License and Copyright /* -------------------------------------------------------------------------  * Dotnet Commons IO  *  *  * This library is free software; you can redistribute it and/or modify it   * under the terms of the GNU Lesser General Public License as published by   * the Free Software Foundation; either version 2.1 of the License, or   * (at your option) any later version.  *  * This library is distributed in the hope that it will be useful, but   * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY   * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License   * for more details.   *  * You should have received a copy of the GNU Lesser General Public License   * along with this library; if not, write to the   *   * Free Software Foundation, Inc.,   * 59 Temple Place,   * Suite 330,   * Boston,   * MA 02111-1307   * USA   *   * -------------------------------------------------------------------------  */ #endregion using System; using System.Collections; using System.Globalization; using System.IO; namespace Dotnet.Commons.IO {     class MainClass{        /// <summary>The number of bytes in a kilobyte.</summary>     public const long ONE_KB = 1024;     /// <summary>The number of bytes in a megabyte.</summary>     public const long ONE_MB = ONE_KB * ONE_KB;     /// <summary> The number of bytes in a gigabyte.</summary>     public const long ONE_GB = ONE_KB * ONE_MB;     /// --------------------------------------------------------------------------     /// <summary>     /// Returns a human-readable version of the file size (original is in bytes).     /// </summary>     /// <param name="size">The number of bytes.</param>     /// <returns>A human-readable display value (includes units).</returns>     /// --------------------------------------------------------------------------     public static string DisplaySize(long size)      {       string displaySize;       if (size / ONE_GB > 0)        {         displaySize = Convert.ToString(size / ONE_GB) + " GB";       }        else if (size / ONE_MB > 0)        {         displaySize = Convert.ToString(size / ONE_MB) + " MB";       }        else if (size / ONE_KB > 0)        {         displaySize = Convert.ToString(size / ONE_KB) + " KB";       }        else        {         displaySize = Convert.ToString(size) + " bytes";       }       return displaySize;     }    } }