Windows:列出并启动与扩展名关联的应用程序
时间:2020-03-05 18:42:34 来源:igfitidea点击:
如何确定与特定扩展名相关的应用程序(例如.JPG),然后确定该应用程序的可执行文件所在的位置,以便可以通过调用System.Diagnostics.Process.Start(...)来启动该可执行文件。
我已经知道如何读写注册表。注册表的布局使我们很难以标准方式确定与扩展名关联的应用程序,显示名称和可执行文件的位置。
解决方案
回答
文件类型关联存储在Windows注册表中,因此我们应该能够使用Microsoft.Win32.Registry类来读取为哪种文件格式注册了哪个应用程序。
这里有两篇文章可能会有所帮助:
- 在.NET中读写注册表
- 使用C#的Windows注册表
回答
样例代码:
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); } } } } }
回答
@aku:别忘了HKEY_CLASSES_ROOT \ SystemFileAssociations \
不知道它们是否在.NET中公开,但是有COM接口(IQueryAssociations和朋友)可以处理此问题,因此我们不必在注册表中乱七八糟,希望下一个Windows版本中的内容不会更改
回答
就像Anders所说的那样,使用IQueryAssociations COM接口是一个好主意。
这是来自pinvoke.net的示例
回答
同样是HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ FileExts \
.EXT \ OpenWithList键,用于"打开宽度..."列表(选项的'a','b','c','d'等字符串值)
.EXT \ UserChoice键,用于"始终使用选定的程序来打开这种文件"(" Progid"字符串值的值)
所有值都是键,使用与上面示例中的docName相同的方式。