If you’ve ever needed to get hold of the duration of a media file such as an MP4 or MP3 file in C#, you’ve probably discovered there are a whole bunch of possible techniques, and its hard to know which one to pick. None seem ideal, and all either involve referencing other libraries or using a bit of PInvoke.

My preference is to get the value from the Windows Shell, and the the helpful Microsoft.WindowsAPICodePack-Shell NuGet package contains wrappers for the relevant APIs. With this  NuGet package installed, we can very simply ask for the video duration as a TimeSpan like this:

private static TimeSpan 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);
    }
}

And that’s all there is to it. Has worked well for me so far.

Comments

Comment by Sunjay Kalsi

It seems to be a very difficult task to get to the duration of a movie file in C#. I'm interested in in your post, but looking at the Shell nuget page - it seems to be quite an old package. I need something that's gonna work for UWP Windows 10 App. Have you got any suggestions?

Sunjay Kalsi
Comment by Mark Heath

I'd expect in UWP the easiest way is to load it into a mediaplayer and ask for duration.

Mark Heath
Comment by Neurovitan Neurovitan

This was very helpful and works as it should. Thanks!

Neurovitan Neurovitan
Comment by Anil Kumar

I needed to track the no.of hours of video lectures I learn per day. For that I made a simple console app which uses above mentioned code to the duration of a lecture. Thanks Mark.

Anil Kumar
Comment by Doaa

Thanks a lot. Iam using dotet core and I installed this package. My question will it work with linux?

Doaa
Comment by Mark Heath

unfortunately not, this makes use of Windows APIs

Mark Heath
Comment by Om.ar Ni.cef Gonz.alez Ri.os

I tried to get the Media File Duration by using, instead of a local path, an URL but, I got a message "The given path's format is not supported."
Is there a way, using the NAudio, that helps to get this?
Thanks!

Om.ar Ni.cef Gonz.alez Ri.os
Comment by Adi Putra

This works on my Windows 10 machine. But why in windows server 2012, the prop.ValueAsObject has null value? Thus the method can't get the duration.

Adi Putra