问题
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#?
回答1:
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));
}
}
}
回答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.
来源:https://stackoverflow.com/questions/6235081/getting-specific-file-attributes