Search code examples
c#shellvideoduration

Access a media file's shell property "Length" (aka Duration) in C#


I have noticed that in the shell properties of every media file in windows 7, the duration of a video file is actually called "length". Anyone knows a quick way of accessing the length property using shell?


Solution

  • So I found a really short and quick way for accessing the "Length" shell property of a media file, or any shell property for that matter, as long as you know the equivalent index number of that property.

    First of you need to add a reference in your project to shell32 like this:

    1. Right click project

    2. Click Add reference

    3. Click .COM tab in Add reference window

    4. Select Microsoft Shell Controls and Automation

    5. Click OK

    Then add using Shell32; in your code-behind. And now you can extract the length property for each media file in a folder with the GetDetailsOf() method, in a foreach loop:

    string[] supportedExtensions = new[] { ".mov", ".mp4", ".avi", ".mpeg", ".mpg", ".wmv", ".mkv", ".m4v", ".flv" };
    
    var allFiles = Directory.GetFiles(SelectedFolderPath, "*.*", SearchOption.TopDirectoryOnly).Where(s => supportedExtensions.Contains(System.IO.Path.GetExtension(s).ToLower()));
    
    foreach (string name in allFiles)
    
    {
       Shell shell = new Shell();
       Folder rFolder = shell.NameSpace(@SelectedFolderPath);
       FolderItem rFiles = rFolder.ParseName(System.IO.Path.GetFileName(name));
       string videosLength = rFolder.GetDetailsOf(rFiles, 27).Trim();
    }
    

    Where, "SelectedFolderPath" should be the folder you wish to scan and the number 27 you see as a parameter in the GetDetailsOf method, is the index number for the "Length" Shell property, specificaly.

    So now you have the duration of a media file inside the string "videosLength" in a ##:##:## format.

    Hope this helps! Cheers!