Denis
Denis

Reputation: 12087

On a Windows machine is there a way to programmatically find out which application is responsible for opening files with a particular extension?

On a Windows machine, is there a way to programmatically find out which application is responsible for opening files with a particular extension? Suppose I want to find out programmatically which application is responsible for opening .PDF files. (don't care if you have C# or VB.NET code)

Upvotes: 2

Views: 736

Answers (3)

Avish
Avish

Reputation: 4626

The command-line command ASSOC finds file associations, and the command FTYPE finds actions assigned to them:

C:\> assoc .docx
.docx=Word.Document.12

C:\> ftype Word.Document.12
Word.Document.12="C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" /n /dde

You can probably invoke them programmatically from any script.

From C#, you'd want to do something like this:

private string ShellCommand(string command)  
{
  var psi = new ProcessStartInfo("cmd", "/c " + command) {
    RedirectStandardOutput = true,
    CreateNoWindow = true
  };
  var p = Process.Start(psi);
  return p.StandardOutput.ReadToEnd();
}

private string FindDefaultProgram(string extension)
{
   assoc = ShellCommand("assoc " + extension).Split('=')[1];
   program = ShellCommand("ftype " + assoc).Split('=')[1];
   return program;
}

Haven't tested any of this, so take it with a grain of salt, but this should get you on the right track.

Upvotes: 3

Torben Koch Pløen
Torben Koch Pløen

Reputation: 977

Well, you will start out by looking in the registry in the following position:

HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.pdf\OpenWithList

There will be one or more keys from a and onwards, which point to the program used for opening a file of that type:

using Microsoft.Win32;
var key = Registry.CurrentUser
    .OpenSubKey("Software")
    .OpenSubKey("Microsoft")
    .OpenSubKey("Windows")
    .OpenSubKey("CurrentVersion")
    .OpenSubKey("Explorer")
    .OpenSubKey("FileExts")
    .OpenSubKey(".doc")
    .OpenSubKey("OpenWithList");

var firstProgram = key.GetValue("a"); // E.g. Winword.exe

You might want to split the assignment to key into several statements with null checks ;-)

Hope this helps!

Upvotes: 3

poke
poke

Reputation: 388303

I won’t give you code but rather tell you where this information is stored – I’m sure you can figure out the rest on your own :)

So, all that data is stored inside the registry, in HKEY_CLASSES_ROOT. Taking .pdf as an example, there is a key .pdf which contains AcroExch.Document as it’s default value (on my setup at least).

Again in HKEY_CLASSES_ROOT there is a key AcroExch.Document\Shell\Open\Command and that one contains "C:\Program Files (x86)\Adobe\Acrobat 8.0\Acrobat\Acrobat.exe" "%1" as its value. And that’s what is being used on my computer to open a PDF file.

Upvotes: 2

Related Questions