Associating a File Type With an Application in C#

If your application is an editor or processor for a certain type of data, you can associate your application with a file type such that by clicking that file, or if you run the application directly, it can do something else (such as create a new file of that type or give the user a chance to locate the file manually).
 
The steps are very simple:-
 
Step 1: Open a new Windows Form Application project in Visual Studio. The project is created with a default form - Form1. We will use Form1 as the default form if the program is run with no files.

Untitled-9.gif
 
Step 2: Add a new form - Form2 (you can change the name if you want). This will be the form that displays if the program is run by double-clicking a file.
 
Step 3: In the constructor for Form2 add a string parameter. This will be the filename of the file clicked.
 
Step 4: Within Form2, add whatever controls and processing is needed to work with this type of file.

Untitled-3.gif
 
Step 5: Within Form1, add whatever controls and processing is needed if the program is run with no files.
 
Step 6: Open the main program for the application - Program.cs.
Locate the main method - Main().
 
Step 7: Insert a string array as a parameter to Main(); ie Main(string[] args). This parameter will take any arguments that are given when the program is run. Double-clicking a file simply runs the associated program with the name of the file as an argument.
 
Step 8: Determine which form to call depending on whether or not there are parameters. If there are parameters, create Form2 with arg[0] as parameter to the   constructor.

Untitled-5.gif
 
Step 9: Build your application and move the executable to your preferred directory.
 
Step 10: Now associate files of the desired type with your program.
 
If you are using Windows XP this can be done in Windows Explorer by right-clicking a file of the desired type, and selecting either "open" (if the file does not already have an association) or "open with" (if it does) and following the dialogue boxes to locate your program. Or you can use "tools/Folder options.../file types" in the menu bar to do the same thing.

You can set flags to ensure your new program is always called to open this type of file by default.

Untitled-7.gif
Alternatively, you can download the sample project which not only illustrates these steps but also, as a bonus, shows how to get your program to set file association automatically by modifying the registry. It even puts your file type in the new-files context menu so you can create a new file by right-clicking the Desktop and selecting "new"!

Up Next
    Ebook Download
    View all
    Learn
    View all