在 C# 中是否有一种简单的方法可以通过扩展名来确定文件是什么?

发布于 2024-08-14 10:51:03 字数 164 浏览 2 评论 0原文

在 C# 中是否有一种简单的方法可以通过扩展名来确定文件是什么?例如,如果我传递文件扩展名“.txt”,那么它将返回“文本文档”,或者如果我传递“.pdf”,它将返回“Adobe Acrobat Reader”。我看到 Windows 资源管理器中内置了这种行为,位于“类型”列下。有没有办法在 C# 中模仿这个?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

葬シ愛 2024-08-21 10:51:03

如果您想获得资源管理器实际显示的内容并愿意使用 COM 互操作,您可以使用 Shell.Application 类以最少的代码量获得它。如果要添加引用,请浏览到 X:\windows\system32\shell32.dll,它将导入 shell32 的类型库。然后只需使用代码:

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

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);
}
﹏雨一样淡蓝的深情 2024-08-21 10:51:03

使用注册表类查询 HKCR 配置单元。

Use the Registry class to query the HKCR hive.

多情癖 2024-08-21 10:51:03

看一下这个类

C# FileAssociation 类

Have a look at this class

C# FileAssociation Class

温柔一刀 2024-08-21 10:51:03

检查注册表;你可以从那里获取该数据

Check the registry; you can get that data from there

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文