Finding the default application for opening a particular file type on Windows

Viewed 51393

I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type.

I know that, for example, if you just want to open a file using that application you can use something like:

System.Diagnostics.Process.Start( "C:\...\...\myfile.html" );

to open an HTML document in the default browser, or

System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" );

to open a text file in the default text editor.

However, what I want to be able to do is to open files that don't necessarily have a .txt extension (for example), in the default text editor, so I need to be able to find out the default application for opening .txt files, which will allow me to invoke it directly.

I'm guessing there's some Win32 API that I'll need to P/Invoke in order to do this, however a quick look with both Google and MSDN didn't reveal anything of much interest; I did find a very large number of completely irrelevant pages, but nothing like I'm looking for.

6 Answers

You can check under registry section HKEY_CLASSES_ROOT for the extension and action details. Documentation for this is on MSDN. Alternatively, you can use the IQueryAssociations interface.

Doh! Of course.

HKEY_CLASSES_ROOT\.txt

includes a reference to

HKEY_CLASSES_ROOT\txtfile

which contains a subkey

HKEY_CLASSES_ROOT\txtfile\shell\open\command

which references Notepad.

Sorted, many thanks!

Bart

You can just query the registry. First get the Default entry under HKEY_CLASSES_ROOT\.ext

That will give you the classname. For example .txt has a default of txtfile

Then open up HKEY_CLASSES_ROOT\txtfile\Shell\Open\Command

That will give you the default command used.

Related