Getting specific file attributes

rafale picture rafale · Jun 4, 2011 · Viewed 10k times · Source

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#?

Answer

Khepri picture Khepri · Jun 4, 2011

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));
        }
    }
}