Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get video file duration from metadata

Tags:

I am trying to read metadata from a file. I only need the Video -> Length property, however I am unable to find a simple way of reading this information.

I figured this would be fairly easy since it is visible by default in Explorer, however this looks to be way more complicated than I anticipated. The closest I came was using:

Microsoft.DirectX.AudioVideoPlayback.Video video = new Microsoft.DirectX.AudioVideoPlayback.Video(str); double duration = video.Duration; 

However this throws a LoaderLock exception, and I don't know how to deal with it.

Any ideas?

like image 489
David Božjak Avatar asked Aug 10 '09 19:08

David Božjak


1 Answers

Many of these details are provided by the shell, so you can do this by adding a reference to the COM Library "Microsoft Shell Controls and Automation" (Shell32), and then using the Folder.GetDetailsOf method to query the extended details.

I was recently looking for this and came across this very question on the MSDN C# General forums. I wound up writing this as an extension method to FileInfo:

    public static Dictionary<string, string> GetDetails(this FileInfo fi)     {         Dictionary<string, string> ret = new Dictionary<string, string>();         Shell shl = new ShellClass();         Folder folder = shl.NameSpace(fi.DirectoryName);         FolderItem item = folder.ParseName(fi.Name);          for (int i = 0; i < 150; i++)         {             string dtlDesc = folder.GetDetailsOf(null, i);             string dtlVal = folder.GetDetailsOf(item, i);              if (dtlVal == null || dtlVal == "")                 continue;              ret.Add(dtlDesc, dtlVal);         }         return ret;     } 

If you're looking for specific entries, you can do something similar, though it will be far faster to find out what index those entries are at (Length is index 27 I believe) and just query those. Note, I didn't do much research into whether or not the index can change (I doubt it), which is why I took the dictionary approach.

like image 74
chsh Avatar answered Oct 23 '22 12:10

chsh