Is there an easy way to determine what a file is by its extension in C#?

馋奶兔 提交于 2019-12-18 17:54:27

问题


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


回答1:


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



回答2:


Use the Registry class to query the HKCR hive.




回答3:


Have a look at this class

C# FileAssociation Class




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!