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.
All current answers are unreliable. The registry is an implementation detail and indeed such code is broken on my Windows 8.1 machine. The proper way to do this is using the Win32 API, specifically AssocQueryString:
Relevant documentation:
Sample usage:
Doh! Of course.
includes a reference to
which contains a subkey
which references Notepad.
Sorted, many thanks!
Bart
Here is a blog post with about this topic. The code samples are in VB.net, but it should be easy to port them to C#.
Link NUGET File Association
Usage is simple, for instance to add all allowed file extensions to a context menu:
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.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.