There are two main ways to get the length of a video file in C#:
- Use a Shell object (found in shell32.dll in the system32 directory) to get the video length from the file metadata.
- Instantiate a WindowsMediaPlayer object (found in wmp.dll if WMP is installed on your machine), load the file into it and then get the length from the corresponding object property.
The advantage of the first method is that WMP does not need to be installed on your machine for it to function. This makes it the only option for many servers as well as systems running an “N” edition of Windows which does not contain WMP by default. The second method, however, is simpler to use and on my machine offered a very slight performance advantage (~5%) when looping through a collection of 20 files. Here are both methods:
Method 1 - Shell
Don’t forget to create a reference to shell32.dll found in the system32 folder.
You may need to apply the [STAThread] attribute to the entry point of your application for this to function properly.
Method 2 – WMP
Don’t forget to create a reference to wmp.dll found in the system32 folder.