The Wayback Machine - https://web.archive.org/web/20120912235451/http://www.codeguru.com:80/columns/vb/adding-file-associations.htm

Adding File Associations

Introduction

For some reason, setting file associations is still somewhat of a mystery to many a developer. Why it's a mystery is because very few people actually know the correct way to set file associations for applications. Have you ever wondered why a program such as Microsoft Word automatically knows that it should open a file with a .doc. or .docx extension? Well, there is your answer already! The installer. Plain and simple.

The Myths

  1. It just happens, automatically that is
  2. Set all the associations in the registry, when the program is run for the first time
  3. Set it up yourself
  4. Erm, what is a file association?

The Reality

  1.  Almost true. The question you should be asking yourself is how does it happen automatically?
  2. Yes. That can work. IMHO, it is not really good practice. The application, especially registry settings such as a program's associations can be difficult to fathom, best to do properly after the fact. These should have been done, before the program was launched.
  3. No. No. No. No. Imagine doing this for Microsoft Word or Excel; a normal PC user will not have all the knowledge to do this
  4. No answer

Solution

The solution has been staring us straight in the eyes. Have you guessed it? If not, the solution to our problem is to create a setup program (or installer package) that can do all this little, but very important work for us. It's as simple as that. How? Let me tell you and show you. First, we need to create a small program in either VB.NET or C# - just to verify our methods work properly, and then we'll create the installer package(s).

Fire up Visual Studio and create a Windows Forms project, and add the following controls to your Form :

ControlPropertySetting
MenuStrip Text &File
ToolStripMenuItem Text &Save
ToolStripMenuItem Text &Open
ToolStripMenuItem Text E&xit
RichTextBox Name rtbHTG_Associate
  Dock Fill
OpenFileDialog Name OpenFileDialog1
SaveFileDialog Name SaveFileDialog1

Coding - Part 1

Let us get a working program first, so that we can experiment with the file associations and how they work. We will first add code to open a file and to save a file. After that, we'll make the installers, and add the necessary code to make our file association work properly.

Add the System.IO namespace :

VB.NET

Imports System.IO

C#

using System.IO;

Add the following code to the OpenToolStripMenuItem_Click event :

VB.NET

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        Dim myStream As Stream = Nothing 'Initialise Stream object

        OpenFileDialog1.InitialDirectory = "c:\" 'Set initial directory
        OpenFileDialog1.Filter = "htg files (*.htg)|*.htg|All files (*.*)|*.*" 'File types allowed
        OpenFileDialog1.FilterIndex = 1 'First Filter = HTG
        OpenFileDialog1.RestoreDirectory = True

        If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            rtbHTG_Associate.LoadFile(OpenFileDialog1.FileName, _
                   RichTextBoxStreamType.PlainText) 'Load Selected file into RTB
        End If

    End Sub

C#

        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
         
            OpenFileDialog1.InitialDirectory = "c:\\"; //Set initial directory
            OpenFileDialog1.Filter = "htg files (*.htg)|*.htg|All files (*.*)|*.*"; //Set file extension filters
            OpenFileDialog1.FilterIndex = 1; //File extension 1 = HTG
            OpenFileDialog1.RestoreDirectory = true;

            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                rtbHTG_Associate.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.PlainText); //Load Selected file into RTB
            }
        }

Write the code to save a file :

VB.NET

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click

        Dim myWriter As StreamWriter 'To write output
        Dim myStream As FileStream 'Stream object

        SaveFileDialog1.Filter = "htg files (*.htg)|*.htg|All files (*.*)|*.*" 'Filters
        SaveFileDialog1.FilterIndex = 1
        SaveFileDialog1.RestoreDirectory = True

        If SaveFileDialog1.ShowDialog() = DialogResult.OK Then 'If valid selection
            myStream = SaveFileDialog1.OpenFile()
            myWriter = New StreamWriter(myStream) 'Write file contents

            If (myStream IsNot Nothing) Then 'If there is text

                Dim myItem As Object

                For Each myItem In rtbHTG_Associate.Text 'Write it
                    myWriter.Write(myItem.ToString)
                Next

                myWriter.Close() 'close all handles
                myStream.Close()
            End If
        End If

    End Sub

C#

        private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamWriter myWriter = null; //To write output
            Stream myStream = null; //Stream object

            SaveFileDialog1.Filter = "htg files (*.htg)|*.htg|All files (*.*)|*.*"; //Filters
            SaveFileDialog1.FilterIndex = 1;
            SaveFileDialog1.RestoreDirectory = true;

            if (SaveFileDialog1.ShowDialog() == DialogResult.OK) //If valid selection
            {
                myStream = SaveFileDialog1.OpenFile();
                myWriter = new StreamWriter(myStream); //Write file contents

                if ((myStream != null)) //If there is text
                {
                    object myItem = null;

                    foreach (object myItem_Loop in rtbHTG_Associate.Text) //Write it
                    {
                        myItem = myItem_Loop;
                        myWriter.Write(myItem.ToString());
                    }
                    myWriter.Close(); //close all handles
                    myStream.Close();
                }
            }


        }

Adding File Associations - Page 2

When we run our program now, we will be able to save and open files with the .htg extension. Try it now. If you encounter any problems, feel free to look at the download I am supplying.

Now the fun starts!

Creating the Installer

These steps are exactly the same in VB.NET and C#, so I will not make any distinctions between the two now.

Follow these steps to add your installer :

  • Add a Setup Project to your solution by clicking on File -> Add Project ->New project -> Setup & Deployment Projects ->Setup Project.
  • Right-click your Setup Project in Solution Explorer and select View, then select File Types.
  • Right-click File types on target machine. Click Add File Type.
  • You will notice that New document Type#1 was added, and an &open item just underneath it. The New Document Type#1 can be any document type you want - change it to something descriptive and unique. Be careful not to overwrite existing file types! Use HTG_Extension here, because, as far as I am aware, there isn't any program that uses that extension or description.
  • In the Properties window for New Document Type#1, you will need to change a few properties.
    • Command : Change to the application that you want to run, in other words, ADD YOUR OUTPUT FILE.
    • Description : This is the description of the file type (Describe the type of file or program it belongs to).
    • Extensions : Here you can supply your list of extensions for your chosen Program. For example htg.
    • Icon : This will associate the icon with your file type. This you will notice in Window Explorer / My Computer.
  • Click on &Open. This is an action that is available if you right-click on the file. The default action is what happens when you double click on the file. In the Properties Window, make sure Verb is set to open.

Have a look at MSDN for a better understanding of File extensions, file associations, and commands such as Verbs.

Build your setup file, and make sure that there are no errors.

I know you're anxious to see this in action; me too! All we need to do now is to update our code to accept the Open Verb when a user double clicks on any of our files in Windows Explorer / My Computer.

Coding  - Part 2

The following function and sub assist us in obtaining the name of the file ( that was double clicked upon ) from My Computer / Windows Explorer. It then, because of the Verb we set, launches its associated program. This works similar to double clicking a Microsoft Word document. Then, lastly, displays the file name inside our program's title bar along with the text in the Rich Text Box

VB.NET

    Private Function GetDoubleClickedFileName(ByVal StrFullPath As String) As String
        Dim intPos As Integer 'To locate last \

        intPos = InStrRev(StrFullPath, "\") 'Get last Index of "\" Could have used LastIndexOf as well
        GetDoubleClickedFileName = Mid$(StrFullPath, intPos + 1) 'Get the name of file

    End Function

    Private Sub OpenFilesByDoubleClicking()
        Dim strFileExt As String 'Get File Extension

        Dim strFileContents As String 'Get Contents of File

        Dim CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.CommandLineArgs 'Get Command Line Arguments ( &open )

        For i As Integer = 0 To CommandLineArgs.Count - 1 'Loop through all arguments

            strFileExt = System.IO.Path.GetExtension(CommandLineArgs(i)) 'Get the filename extension

            Select Case strFileExt


                Case ".htg" 'This is to open a file with associated extension *.htg

                    strFileContents = My.Computer.FileSystem.ReadAllText(CommandLineArgs(i)) 'Read content

                    rtbHTG_Associate.Text = strFileContents 'Load content into RTB

                    Me.Text = GetDoubleClickedFileName(CommandLineArgs(i)) & " - HTG_AssociateFiles" 'Name of program + file opened

            End Select
        Next
    End Sub

C#

        private void OpenFilesByDoubleClicking()
        {
            try
            {
                string strFileExt = null;
                //Get File Extension

                string strFileContents = null;
                //Get Contents of File

                string[] CommandLineArgs = Environment.GetCommandLineArgs();
                //Get Command Line Arguments ( &open )

                //Loop through all arguments
                if (CommandLineArgs.Length > 1)
                {
                    for (int i = 0; i <= CommandLineArgs.Length; i++)
                    {

                        strFileExt = System.IO.Path.GetExtension(CommandLineArgs[i]);
                        //Get the filename extension

                        switch (strFileExt)
                        {


                            case ".htg":
                                //This is to open a file with associated extension *.htg

                                strFileContents = File.ReadAllText(CommandLineArgs[i]);
                                //Read content

                                rtbHTG_Associate.Text = strFileContents;
                                //Load content into RTB

                                this.Text = GetDoubleClickedFileName(CommandLineArgs[i]) + " - HTG_AssociateFiles";
                                //Name of program + file opened
                                break;
                        }

                    }


                }
            }
            catch (Exception es)
            {
            }
        }

Build both your projects. Install your program via the installer you have just created. Launch your program and save a file (if you haven't yet saved a file earlier). Exit your program. Navigate to where you have saved your file. Double click on it. Voila! That is it! It wasn't so tough now, was it?

Conclusion

I hope you have learned something from this article and that you have enjoyed it. To me, it was a great deal of fun demonstrating this. Until next time! Good luck & cheers!

Related Articles

Downloads

IT Offers

Comments

  • There are no comments yet. Be the first to comment!

Whitepapers and More

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds