🔒 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
  • 337
    Views
  • 1
    Participants
Last reply from:
zackmark29

Trending Topics

Online now

Members online
1,205
Guests online
2,724
Total visitors
3,929

Forum statistics

Threads
2,331,843
Posts
29,260,713
Members
1,147,852
Latest member
applemaple11
Back
Top