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

Trending Topics

Online now

Members online
1,034
Guests online
3,452
Total visitors
4,486

Forum statistics

Threads
2,307,129
Posts
29,176,770
Members
1,193,251
Latest member
Hoffs5190
Back
Top