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.

Vote on HN