views:

1095

answers:

4

How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).

I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.

A: 

The file type associations are stored in the Windows registry, so you should be able to use the Microsoft.Win32.Registry class to read which application is registered for which file format.

Here are two articles that might be helpful:

Erik Öjebo
+5  A: 

Sample code:

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
Better to use IQueryAssociations
Simon Gillbee
+2  A: 

@aku: Don't forget HKEY_CLASSES_ROOT\SystemFileAssociations\

Not sure if they are exposed in .NET, but there are COM interfaces (IQueryAssociations and friends) that deal with this so you don't have to muck around in the registry and hope stuff does not change in the next windows version

Anders
+3  A: 

Like Anders said - It's a good idea to use the IQueryAssociations COM interface. Here's a sample from pinvoke.net

Barakando
The link included is for AssocCreate. The link to AssocQuery is this:http://www.pinvoke.net/default.aspx/shlwapi.AssocQueryString
epotter