Wednesday, April 11, 2012

Make C# Program Default Program for Opening File Types

Windows saves for many file extensions a default program, with which the file is opened when clicked.
For example the extension ".docx" is assigned to Word and ".txt" to a text editor.
In this post I want to show, how to assign a new or existing file extensions to the own C# application (or another program), meaning to make it default program for opening these files.

But where is this assignment saved at all? In the Windows registry. To change the assignment, we just have to change the right keys. The sample application doing this, needs administrative rights on one hand, on the other hand I expect basic knowledge about work in the registry.
Who is not so experienced in these fields, should first read the linked posts.

In the registry for every registered file ending in the super category HKEY_CLASSES_ROOT there is a key. For example with the name ".docx".
For our needs it is sufficient to know, that the default value of this key contains the name of the application, with which the files are opened by default. With this name there is furthermore a key in HKEY_CLASSES_ROOT, which describes the application.
In this key the subkey chain "shell - Open - Command" is important.
In "Command" the default value contains the link to the executable file of the application, so for example "C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE". If the path is appended a "%1" this means that the program is given the file to be opened as parameter, in C# we find this path then in the command line arguments.
The following code snippet creates the descibed registry structure (using Microsoft.Win32 is needed):

                RegistryKey Standards = Registry.ClassesRoot;
                RegistryKey XYKey = Standards.OpenSubKey(".xyz", true);
                XYKey.SetValue("", "MyCSharpApp");

                RegistryKey SCKey = Standards.CreateSubKey("MyCSharpApp");
                RegistryKey ShKey = SCKey.CreateSubKey("shell");
                RegistryKey OpKey = ShKey.CreateSubKey("Open");
                RegistryKey CmdKey = OpKey.CreateSubKey("Command");
                CmdKey.SetValue("", Application.StartupPath + "\\MyCSharpApp.exe %1");