Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run time/length info for all media files in a folder

Tags:

c#

media

If there are multiple media files in a folder like so:

MediaFiles(folder)

-> file1.mp4
-> file2.mp4
...

When we select all the files and

Right Click -> Properties

In the Properties windows on the Details Tab there is a Length field that shows the total runtime of the media files together like this:

Properties windows

Is it possible to get this info using C#?

like image 564
Codehelp Avatar asked Sep 01 '25 22:09

Codehelp


1 Answers

As indicated in this link, with the help of the Microsoft.WindowsAPICodePack-Shell nuget package, you can get the total length as follows;

static void Main(string[] args)
{
    DirectoryInfo dir = new DirectoryInfo(@"C:\to\your\path");
    FileInfo[] files = dir.GetFiles("*.mp4");

    var totalDuration = files.Sum(v => GetVideoDuration(v.FullName));
}

public static double GetVideoDuration(string filePath)
{
    using (var shell = ShellObject.FromParsingName(filePath))
    {
        IShellProperty prop = shell.Properties.System.Media.Duration;
        var t = (ulong)prop.ValueAsObject;
        return TimeSpan.FromTicks((long)t).TotalMilliseconds;
    }
}
like image 132
ibubi Avatar answered Sep 03 '25 11:09

ibubi