Getting specific file attributes
Asked Answered
Q

2

9

I've got a simple WCF service that lets clients/consumers upload image, audio or video files to it. After the upload, the service is supposed to analyze the file and somehow retrieve the following attributes:

Image: width, height, date taken, program used

Audio: runtime, artist, album, genre, bitrate, publication year

Video: runtime, width, height, frames/sec, video bitrate, audio bitrate

Apparently Windows can get and display these attributes pretty easily, but how do I do it in C#?

Quicklime answered 4/6, 2011 at 6:5 Comment(1)
possible duplicate of Read/Write 'Extended' file properties (C#)Relique
J
7

Courtesty of this thread.

I've verified this gets all file attributes including the extended attributes.

In your project go to 'Add Reference' -> COM -> 'Microsoft Shell Controls and Automation'

Add that, and again courtesy of said thread, a C# method to read the attributes of the files in a directory. (I'm still researching to see if it's possible to perform this functionality on a specific file. If not you could always pass the filename in question and verify to only get the attributes out for that file.)

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine("{0}\t{1}: {2}", i, arrHeaders[i], objFolder.GetDetailsOf(item, i));
        }
    }
}
Joyous answered 4/6, 2011 at 6:26 Comment(2)
Be aware that this solution does not work on Windows XP. When accessing Shell32 from XP you get a COM exception.Scrutator
To the best of my knowledge/experience, this works fine on XP. What problem are you seeing?Joyous
A
2

The simplest way to access that information is to let the (Explorer) Shell do it for you and just ask (via Windows Property System) for it. And the simplest way to do that from C# is probably to use the Windows API Code Pack for .NET.

Specifically you're going to want to gain access to the Property Store. For help getting started, look in the Samples folder at the PropertiesEditDemo project.

You can do it yourself by reading all the metadata for the file, but the problem is then your program has to know all the available metadata for all the available file types. I generally prefer to hang on the Shell for that knowledge.

Auditorium answered 4/6, 2011 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.