views:

405

answers:

4

Is there an easy way to determine what a file is by its extension in C#? For example if I pass a file extension of ".txt" then it will return "Text Document" or if I pass it ".pdf" it will return "Adobe Acrobat Reader". I see this behavior built into Windows Explorer, under the "Type" column. Is there a way to mimic this in C#?

A: 

Check the registry; you can get that data from there

Pierreten
Thats a bit broad. How about some links?
astander
I figured googling c# "registry filetype" isn't Brian surgery
Pierreten
Ya, and spelling brain isn't roket science either :p
John Weldon
Same goes for rocket haha, sorry I had to.
Nate Shoffner
+1  A: 

Use the Registry class to query the HKCR hive.

Traveling Tech Guy
+1  A: 

Have a look at this class

C# FileAssociation Class

astander
+3  A: 

If you want to get what explorer actually shows and are willing to use COM inter-op you can use the Shell.Application class to get it with the minimum amount of code. If you go to add a reference, browse to X:\windows\system32\shell32.dll that will import shell32's type library. Then just use the code:

string GetFileType(string path)
{
   Shell32.ShellClass shell = new Shell32.ShellClass();
   Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(path));

   Shell32.FolderItem item = folder.ParseName(Path.GetFileName(path));
   return folder.GetDetailsOf(item, 2);
}
tyranid
This seems to work perfect. Will this work in all versions of Windows? XP, Vista and Windows 7?
Alan Bryan
It should do, the COM object has been around for ages. But I have only personally tried that code on 7.
tyranid