应用程序是否与给定的扩展相关联?
有时需要让您的应用程序打开文件的默认应用程序。 例如,要打开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; }
我建议按照大卫的回答中的建议但是因为你需要检测一个关联:
要检查文件是否具有关联,您可以使用本机函数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
在这种情况下,最好的方法是尝试打开文档并检测故障。 试图预测文件关联是否到位只会导致您重新实现shell执行API。 因为它们已经存在,所以很难完全正确而且不必要!
@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);
您也将查看注册表以获取该信息。
您可以关注:
HKEY_CLASSES_ROOT\.extension
它通常会导致像HKEY_CLASSES_ROOT\extfile\Shell\Open\Command
然后你会来命令打开文件类型。
根据你正在做的事情,要求宽恕可能是理想的(也就是说,只需打开文件并查看)
所有这些信息都存在于注册表中..您可以导航到HKEY_CLASSES_ROOT,找到扩展名并从那里找到默认处理程序。 但是根据文件的类型和相关的处理程序,你需要涉足到CLSID等等……你可能最好不要去捕获exception。
此信息在注册表中。 例如:
# 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")
- Windows 10 Universal App – 类型存在于“Windows.Foundation.UniversalApiContract”中
- MySQL加载数据Infile
- WPF MVVM和Viewinheritance
- 如何检查2个DirectoryInfo对象是否指向同一目录?
- 如何使用Model First方法使用动态连接字符串,但仍然使用EDMX中的数据模型?
- BackgroundWorker – 在RunWorkerCompleted中CancellationPending更改为false。 为什么?
- 从C#访问ListBox的ScrollViewer
- 7z命令行来压缩文件夹
- 这是DTO的正确使用吗?