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#?
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); }
Use the Registry class to query the HKCR hive.
Have a look at this class
Check the registry; you can get that data from there
来源:https://stackoverflow.com/questions/1851520/is-there-an-easy-way-to-determine-what-a-file-is-by-its-extension-in-c