是与给定扩展关联的应用程序
本文关键字:关联 应用程序 扩展 | 更新日期: 2023-09-27 18:26:34
有时需要让应用程序打开文件的默认应用程序。例如,要打开PDF文件,您可以使用:
System.Diagnostics.Process.Start("Filename.pdf");
要打开图像,只需使用相同的代码和不同的文件名:
System.Diagnostics.Process.Start("Filename.gif");
有些扩展(例如.gif)几乎总是有一个默认的处理程序,即使在基本的Windows安装中也是如此。然而,一些扩展(例如.pdf)通常没有安装应用程序来处理它们。
在这些情况下,在调用Process.Start(fileName).之前,最好先确定应用程序是否与要打开的文件的扩展名相关联
我想知道如何最好地实现这样的东西:
static bool ApplicationAssociated(string extension)
{
var extensionHasAssociatedApplication = false;
var condition = // Determine if there is an application installed that is associated with the provided file extension.;
if (condition)
{
extensionHasAssociatedApplication = true;
}
return extensionHasAssociatedApplication;
}
我建议遵循David回答中的建议,但由于您需要检测关联:
要检查文件是否有关联,可以使用本机函数FindExecutable
,它基本上是Windows资源管理器内部使用的。。。如果没有关联,它给出了一个很好的错误代码(SE_ERR_NOASSOC
)。一旦成功,它将为相应的可执行文件提供一条路径。
它的DllImport
是
[DllImport("shell32.dll")]
static extern int FindExecutable(string lpFile, string lpDirectory, [Out] StringBuilder lpResult);
例如,另一种选择是遍历注册表(不建议使用,因为由于WoW64等几个方面的复杂性):
真正的关联存储在HKEY_CLASSES_ROOT'.pdf
指向的密钥中——在我的例子中是AcroExch.Document
,所以我们签出HKEY_CLASSES_ROOT'AcroExch.Document
。在那里,您可以看到(并更改)将用于启动该类型文件的命令:
HKEY_CLASSES_ROOT'AcroExch.Document'shell'open'command
@Yahia获得点头。我正在为子孙后代发布我的快速解决方案,这样你就可以看到我的做法了。这个代码有很多可能的改进,但这会给你一个想法:
public static bool HasExecutable(string path)
{
var executable = FindExecutable(path);
return !string.IsNullOrEmpty(executable);
}
private static string FindExecutable(string path)
{
var executable = new StringBuilder(1024);
FindExecutable(path, string.Empty, executable);
return executable.ToString();
}
[DllImport("shell32.dll", EntryPoint = "FindExecutable")]
private static extern long FindExecutable(string lpFile, string lpDirectory, StringBuilder lpResult);
在这种情况下,最好的方法是尝试打开文档并检测失败。试图预测文件关联是否到位只会导致重新实现shell执行API。很难做到这一点,因为它们已经存在了,而且是不必要的!
您还需要查看注册表才能获得这些信息。
您可以关注:
HKEY_CLASSES_ROOT'.extension
它通常会导致类似HKEY_CLASSES_ROOT'extfile'Shell'Open'Command
的情况
然后您将进入打开文件类型的命令。
根据你正在做的事情,请求原谅(也就是说,打开文件并查看)
所有这些信息都存在于注册表中。。您可以导航到HKEY_CLASSES_ROOT,找到扩展,然后从那里找到默认的处理程序。但是,根据文件的类型和相关的处理程序,您需要深入了解CLSID等等。。。你可能会更好地捕捉一个异常。
此信息在注册表中。例如:
# Mount the HKCR drive in powershell
ps c:'> new-psdrive hkcr registry hkey_classes_root
ps c:'> cd hkcr:'.cs
# get default key for .cs
PS hkcr:'.cs> gp . ""
(default) : VisualStudio.cs.10.0
...
# dereference the "open" verb
PS hkcr:'.cs> dir ..'VisualStudio.cs.10.0'shell'open
Hive: hkey_classes_root'VisualStudio.cs.10.0'shell'open
Name Property
---- --------
Command (default) : "C:'Program Files (x86)'Microsoft Visual Studio 10.0'Common7'IDE'devenv.exe" /dde
ddeexec (default) : Open("%1")