Get a value from a key converted in file size format: "1gb", "10 mb", "80000" - CSharp System

CSharp examples for System:Math Geometry

Description

Get a value from a key converted in file size format: "1gb", "10 mb", "80000"

Demo Code


using System.Text.RegularExpressions;
using System.Collections.Generic;
using System;/*from   w w w . ja  v  a  2  s . c  o m*/

public class Main{
        /// <summary>
        /// Get a value from a key converted in file size format: "1gb", "10 mb", "80000"
        /// </summary>
        public static long GetFileSize(this Dictionary<string, string> dict, string key, long defaultValue)
        {
            var size = dict.GetValue<string>(key, null);

            if (size == null) return defaultValue;

            var match = Regex.Match(size, @"^(\d+)\s*([tgmk])?(b|byte|bytes)?$", RegexOptions.IgnoreCase);

            if (!match.Success) return 0;

            var num = Convert.ToInt64(match.Groups[1].Value);

            switch (match.Groups[2].Value.ToLower())
            {
                case "t": return num * 1024L * 1024L * 1024L * 1024L;
                case "g": return num * 1024L * 1024L * 1024L;
                case "m": return num * 1024L * 1024L;
                case "k": return num * 1024L;
                case "": return num;
            }

            return 0;
        }
}

Related Tutorials