Adding File Associations

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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 :

Control Property Setting
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();
                }
            }


        }
Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read