如何确定与特定扩展相关联的应用程序(例如.JPG),然后确定该应用程序的可执行文件位于何处,以便可以通过调用System.Diagnostics.Process.Start(…)来启动该应用程序。
我已经知道如何读写registry。 这是registry的布局,使得以标准方式难以确定哪些应用程序与扩展相关联,有什么显示名称以及可执行文件的位置。
示例代码:
using System; using Microsoft.Win32; namespace GetAssociatedApp { class Program { static void Main(string[] args) { const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}"; const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command"; // 1. Find out document type name for .jpeg files const string ext = ".jpeg"; var extPath = string.Format(extPathTemplate, ext); var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(docName)) { // 2. Find out which command is associated with our extension var associatedCmdPath = string.Format(cmdPathTemplate, docName); var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(associatedCmd)) { Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext); } } } } }
像Anders说的那样 – 使用IQueryAssociations COM接口是个好主意。 以下是pinvoke.net的示例
@aku:不要忘记HKEY_CLASSES_ROOT \ SystemFileAssociations \
不知道他们是否暴露在.NET中,但有COM接口(IQueryAssociations和朋友)处理这个问题,所以你不必在注册表中,并希望在下一个Windows版本中不会改变
此外HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ FileExts \
。 EXT \ OpenWithList键为“打开宽度…”列表('a','b','c','d'等字符串值的选择)
。 EXT \ UserChoice键为“始终使用选定的程序来打开这种文件”(“Progid”字符串值的值)
所有值都是键,与上例中的docName使用相同的方式。
文件类型关联存储在Windows注册表中,所以您应该可以使用Microsoft.Win32.Registry类来读取哪个应用程序注册了哪种文件格式。
这里有两篇可能有用的文章: