- Joined
- Mar 25, 2013
- Posts
- 4,237
- Solutions
- 23
- Reaction
- 10,701
- Points
- 2,303
Here's the best method that I'm always using.
I've tested many methods and this is the best.
//Convert bytes to file size format (e.g. 10MB/10GB)
//Get the total length or bytes of video files
//NOW HERE'S THE USAGE:
I've tested many methods and this is the best.
//Convert bytes to file size format (e.g. 10MB/10GB)
C#:
public static string FormatFileSize(long bytes)
{
var unit = 1024;
if (bytes < unit) { return $"{bytes} B"; }
var exp = (int)(Math.Log(bytes) / Math.Log(unit));
return $"{bytes / Math.Pow(unit, exp):F2} {("KMGTPE")[exp - 1]}B";
}
//Get the total length or bytes of video files
C#:
public static long GetFolderSize(string path, string ext, bool AllDir)
{
var option = AllDir ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return new DirectoryInfo(path).EnumerateFiles("*" + ext, option).Sum(file => file.Length);
}
//NOW HERE'S THE USAGE:
C#:
public static void TEST()
{
var folder = @"C:\Users\Mark\Videos";
var bytes = GetFolderSize(folder,"mp4", true); //all files or false if you want the current or single folder only
var totalFileSize = FormatFileSize(bytes);
Console.WriteLine(totalFileSize);
//result: 14.94 GB
}