如何确定与特定扩展关联的应用程序(例如.JPG),然后确定该应用程序的可执行文件所在的位置,以便可以通过调用 System.Diagnostics.Process.Start(...) 来启动它。

我已经知道如何读取和写入注册表。注册表的布局使得以标准方式确定哪些应用程序与扩展关联、有哪些显示名称以及它们的可执行文件所在的位置变得更加困难。

有帮助吗?

解决方案

示例代码:

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键。 list('a','b','c','d'等选项的字符串值)

“<始终使用所选程序打开此类文件”的

EXT \ UserChoice键。 ('Progid'字符串值值)

所有值都是键,使用方法与上例中的 docName 相同。

文件类型关联存储在 Windows 注册表中,因此您应该能够使用 Microsoft.Win32.Registry 类 读取哪个应用程序注册了哪种文件格式。

这里有两篇文章可能会有所帮助:

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top