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

Trending Topics

Online now

Members online
1,166
Guests online
1,978
Total visitors
3,144

Forum statistics

Threads
2,293,791
Posts
29,086,723
Members
1,207,964
Latest member
Adhitya17
Back
Top