Windows 7: Register a New File Associations
Windows 7: Register a New File Associations
Lets say I have a standard Windows Forms application that works with .guy file types (which is nothing but a text file):
This application can be launched from the command line with a file name as an argument:
> TextFilesViewer.exe SampleFile.guy
In this case, the application displays the file contents in the multiline textbox above:
private void ViewerForm_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
string[] lines = File.ReadAllLines(args[1]);
this.txtFileContents.Lines = lines;
}
}
Since this application is the only application that knows how to work with .guy files, we would like to associate this file type with my application.
In order to do that, add a reference to the RegistrationHelper sample. This is an exe that performs the actual registration of the file association and needs to be run with admin privileges. It can be found as a sample project in the WindowsAPICodePack\Samples\Shell\TaskbarDemo\CS\RegistrationHelper folderer
After you have added the reference you should add another file from the samples folder - RegistrationHelper.cs which is found in the WindowsAPICodePack\Samples\Shell\TaskbarDemo\CS\TaskbarDemo\ folder.
This file exposes several static methods that invoke the helper as another process with admin privileges.
private void registerFileTypeToolStripMenuItem_Click(object sender, EventArgs e)
{
string appId = "TextFilesViewer";
RegistrationHelper.RegisterFileAssociations(
appId,
false,
appId,
string.Format("{0} %1", Assembly.GetExecutingAssembly().Location),
".guy");
}
Notice that one of the parameters of RegistrationHelper.RegisterFileAssociations() method is the Application ID which is set to a meaningful name. I’ll talk more on the Application ID in later posts to understand its impact on additional features.
When the user tries to associate the file type, RegistratioinHelper will require admin privileges. If User Account Control (UAC) is enabled on your machine, you will be prompted to allow the registration utility to modify the registry.
After the registration completes, you can double click and .guy files in your machine, and the TextFilesViwer application will be launched to display its content.
Enjoy!