Skip to main content

Parses a file size string into a number. For example, the value "10KB" will be interpreted as 10,240 bytes.

        /// <summary>
        /// Parses a file size into a number. For example, the value "10KB" will be interpreted as 10240 bytes.
        /// </summary>
        /// <param name="argValue">String to parse.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns>The <see cref="long" /> value of <paramref name="argValue" />.</returns>
        /// <remarks>
        /// <para>
        /// Parses a file size of the form: number[KB|MB|GB] into a
        /// long value. It is scaled with the appropriate multiplier.
        /// </para>
        /// <para>
        /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
        /// cannot be converted to a <see cref="long" /> value.
        /// </para>
        /// </remarks>
        public static long ToFileSize(string argValue, long defaultValue)
        {
            if (argValue == null)
            {
                return defaultValue;
            }

            var fileSize = argValue.Trim().ToUpper(CultureInfo.InvariantCulture);
            long multiplier = 1;
            int index;

            if ((index = fileSize.IndexOf("KB", StringComparison.Ordinal)) != -1)
            {
                multiplier = 1024;
                fileSize = fileSize.Substring(0, index);
            }
            else if ((index = fileSize.IndexOf("MB", StringComparison.Ordinal)) != -1)
            {
                multiplier = 1024 * 1024;
                fileSize = fileSize.Substring(0, index);
            }
            else if ((index = fileSize.IndexOf("GB", StringComparison.Ordinal)) != -1)
            {
                multiplier = 1024 * 1024 * 1024;
                fileSize = fileSize.Substring(0, index);
            }

            // Try again to remove whitespace between the number and the size specifier
            fileSize = fileSize.Trim();

            double doubleVal;
            if (double.TryParse(fileSize, NumberStyles.Integer, CultureInfo.InvariantCulture, out doubleVal))
            {
                var longVal = Convert.ToInt64(doubleVal);
                return longVal * multiplier;
            }

            return defaultValue;
        }