Gets the number of bytes as a string. - CSharp System

CSharp examples for System:Byte

Description

Gets the number of bytes as a string.

Demo Code


using System.Globalization;
using System;//from w w  w.j a  va 2s .  c  o  m

public class Main{
        #region ToDisplayString

        /// <summary>
        /// Gets the number of bytes as a string.
        /// </summary>
        /// <param name="bytes">The number of bytes.</param>
        /// <returns>The size in kilobytes or megabytes of the given number of bytes, with 2 decimal places.</returns>
        public static string ToDisplayString(this long bytes)
        {
            double kiloBytes = (bytes / ((double)1024));
            if (kiloBytes > 1024)
            {
                return string.Format(CultureInfo.CurrentCulture, "{0} MB", (kiloBytes / ((double)1024)).ToString("f2", CultureInfo.CurrentCulture));
            }
            else
            {
                return string.Format(CultureInfo.CurrentCulture, "{0} KB", kiloBytes.ToString("f2", CultureInfo.CurrentCulture));
            }
        }
        #endregion

        #region Format

        /// <summary>
        /// Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
        /// </summary>
        /// <param name="format">A composite format string.</param>
        /// <param name="args">An object array that contains zero or more objects to format.</param>
        /// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns>
        public static string Format(this string format, params object[] args)
        {
            return string.Format(format, args);
        }
}

Related Tutorials