🔒 Closed Best Method to Calculate Total File Size on your video folder

Status
Not open for further replies.
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)
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
}
 
Status
Not open for further replies.

About this Thread

  • 0
    Replies
  • 312
    Views
  • 1
    Participants
Last reply from:
zackmark29

Online now

Members online
972
Guests online
1,259
Total visitors
2,231

Forum statistics

Threads
2,276,188
Posts
28,968,163
Members
1,231,157
Latest member
hassano8787h
Back
Top