M. Eng. Dipl.-Ing. (FH) Oliver Kind Mobile Navigation

Diplom-Ingenieur (FH) Maschinenbau-Konstruktionstechnik

Staatlich geprüfter Technischer Assistent für Metallographie und Physikalische Werkstoffanalyse

Programmierer in C#, VB.NET, VB6, C++, php, html, CSS

Um diese Webseite für Sie optimal zu gestalten und fortlaufend verbessern zu können, werden Cookies verwendet. Im Weiteren können Sie auswählen welche Cookies sie akzeptieren möchten. Weitere Informationen zu Cookies erhalten Sie in der Datenschutzerklärung .

Dateigrößen konvertieren

Die Größe einer Datei FileInfo.Length wird als Byte ausgegeben. Für größere Dateien ist die Angabe in Megabyte, Gigabyte hilfreich. Viele Ansätze zur Konvertierung verfolgen hier einen iterativen Weg um die Dimension zu ermitteln. Ich habe hier den Mathematischen weg gewählt.

Die Klasse ist, mit mehr Überladungen einzelner Funktionen, auch in meiner Werkzeugbibliothek enthalten. Der Code wurde zur Darstellung auf dieser Seite vereinfacht, so wurden verweise auf Stringtables entfern.

/*
 * Filename:        clsFileSize.cs
 * Created:         2018-10-20
 * Last modified:   2018-10-20
 * Copyright:       Oliver Kind - 2018
 * License:         LGPL
 * 
 * File Content:
 * 1. FileSize
 *  a. Convert
 *  b. GetDimension
 *  c. SetDimensionlistToComboBox
 * 
 * Desctiption:
 * Class that provides tool to handle file sizes
 * 
 * */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Win32;
using System.Text;
using System.Windows.Forms;

namespace OLKI.Tools.CommonTools.DirectoryAndFile
{
    /// <summary>
    /// Class that convert file sizes from bytes to an defined format
    /// </summary>
    public static class FileSize
    {
        #region Constants
        /// <summary>
        /// Specifies the defaukt byte base for sice conversion
        /// </summary>
        private const ByteBase DEFAULT_BYTE_BASE = ByteBase.IEC;
        /// <summary>
        /// Specifies the defaukt number of decimal digits
        /// </summary>
        private const int DEFAULT_DECIMALS = 2;
        /// <summary>
        /// Specifies the defaukt if the unit should been hidet
        /// </summary>
        private const bool DEFAULT_HIDE_UNIT = false;
        /// <summary>
        /// Specifies the defaukt result format with dimension
        /// </summary>
        private const string DEFAULT_RESULT_FORMAT = "{0} {1}";
        /// <summary>
        /// Unit prefixes for IEC Byte base 1024 in accordance with IEC 60027-2 (International Electrotechnical Commission's standard). Prefix like GiB - Gibi Byte. Used by Microsoft for SI deklaration like GB - Giga Byte
        /// </summary>
        public static readonly string[] UnitPrefix_IEC = new string[7] { "Byte", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
        /// <summary>
        /// Unit prefixes for SI Byte base 1000 in accordance with SI (International System of Units) declaration. Prefix like GB - Giga Byte. Microsoft uses this declaration, but byte base 1024 like IEC
        /// </summary>
        public static readonly string[] UnitPrefix_SI = new string[7] { "Byte", "KB", "MB", "GB", "TB", "PB", "EB" };
        #endregion

        #region Methods
        #region ConvertSize
        /// <summary>
        /// The Byte base for sice conversion 
        /// </summary>
        public enum ByteBase
        {
            /// <summary>
            /// IEC Byte base 1024 in accordance with IEC 60027-2 (International Electrotechnical Commission's standard). Prefix like GiB - Gibi Byte. Used by Microsoft for SI deklaration like GB - Giga Byte
            /// </summary>
            IEC = 1024,
            /// <summary>
            /// SI Byte base 1000 in accordance with SI (International System of Units) declaration. Prefix like GB - Giga Byte. Microsoft uses this declaration, but byte base 1024 like IEC
            /// </summary>
            SI = 1000,
        }

        /// <summary>
        /// The dimension of a byte value
        /// </summary>
        public enum Dimension
        {
            _NotSet_ = -2,
            _Automatic_ = -1,
            NoDimension = 0,
            Kilo = 1,
            Mega = 2,
            Giga = 3,
            Tera = 4,
            Peta = 5,
            Exa = 6
        }

        #region Convert
/// <summary> /// Converts a specified length to the highest or maximum posible dimension, with 2 decimals and the unit /// </summary> /// <param name="length">Specifies the length of an file in byte to convert</param> /// <returns>The converted length</returns> public static string Convert(long length) { return Convert(length, DEFAULT_DECIMALS, DEFAULT_BYTE_BASE, Dimension._Automatic_, DEFAULT_HIDE_UNIT); }
/// <summary> /// Converts a specified length to an forced or maximum posible dimension, with an specified byte base, an specified number of decimal digits and can hide the unit /// </summary> /// <param name="length">Specifies the length of an file in byte to convert</param> /// <param name="decimals">Specifies the number of decimal digits to shown in the result</param> /// <param name="byteBase">Specifies the byte base for conversion</param> /// <param name="dimension">Specifies a forced dimension to convert to</param> /// <param name="hideUnit">Specifies if the unit should been shown or hidet in the result</param> /// <returns>The converted length</returns> public static string Convert(long length, uint decimals, ByteBase byteBase, Dimension dimension, bool hideUnit) { double ConvertedLength = 0; string[] Unit = { }; string NumberFormat = "{0:n" + decimals.ToString() + "}"; string ReturnNumber = string.Empty; // Set the unit array by selected byteBase switch (byteBase) { case ByteBase.SI: Unit = UnitPrefix_SI; break; case ByteBase.IEC: default: Unit = UnitPrefix_IEC; break; } // Get Dimension, if dimension is not preset if (dimension == Dimension._NotSet_ || dimension == Dimension._Automatic_) { dimension = (Dimension)GetHighestDimension(length, byteBase, dimension); } // Get the new length value ConvertedLength = Math.Round(length / Math.Pow((double)byteBase, (double)dimension), (int)decimals); // Return new length, wit or without unit ReturnNumber = string.Format(NumberFormat, ConvertedLength); if (hideUnit) { return ReturnNumber; } return string.Format(DEFAULT_RESULT_FORMAT, new object[] { ReturnNumber, Unit[(int)dimension] }); } #endregion #region GetHighestDimension /// <summary> /// Returns the specified dimension or the maximum posible dimension of a given size, with an specified byte base /// </summary> /// <param name="length">Specifies the length to calculate the dimension with it</param> /// <param name="byteBase">Specifies the byte base faor calculating the dimension</param> /// <param name="forceDimension">Specifie the forced dimension</param> /// <returns>The forced or maximum posible dimension</returns> public static uint GetHighestDimension(long length, ByteBase byteBase, Dimension maxDimension) { // Get the optimal dimension uint HighestDimension = 0; length = Math.Abs(length); if (length > 0) { HighestDimension = (uint)Math.Floor(Math.Log(length, (int)byteBase)); } // Limit to maximum Dimension switch (maxDimension) { case Dimension._NotSet_: // Nothing to do break; case Dimension._Automatic_: // Set dimension to maximum posible by UnitPrefix Array int MaxDimensionByArray = 0; switch (byteBase) { case ByteBase.SI: MaxDimensionByArray = UnitPrefix_SI.Length; break; case ByteBase.IEC: default: MaxDimensionByArray = UnitPrefix_IEC.Length; break; } if (HighestDimension > MaxDimensionByArray - 1) { HighestDimension = (uint)(MaxDimensionByArray - 1); } break; default: // Set to requested maximum dimension HighestDimension = (uint)maxDimension; break; } return HighestDimension; } #endregion #endregion #endregion } }