5,276,801 members and growing! (16,193 online)
Email Password   helpLost your password?
Languages » VB.NET » General     Intermediate License: The Common Development and Distribution License (CDDL)

File Association in VB.NET

By Nickr5

Easily associate your programs with file types (.jpg, .html, .mp3) with just 2 lines of Visual Basic code.
VB 8.0, VB 9.0, VBWindows, .NET, .NET 3.0, .NET 2.0, WinXP, Vista, WinForms, VS2005, VS, Dev

Posted: 29 Apr 2007
Updated: 21 Apr 2008
Views: 37,688
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
14 votes for this Article.
Popularity: 4.06 Rating: 3.54 out of 5
1 vote, 7.1%
1
3 votes, 21.4%
2
1 vote, 7.1%
3
4 votes, 28.6%
4
5 votes, 35.7%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Screenshot - VBFileAssociation1.gif

Introduction

There are many features that every commercial application has, but aren't easy to implement, or find out how to implement, for many people.
Look at Undo/Redo, the Office 2007 Ribbon Bar, spell check, associated file types, and lot's of other small, but powerful features.

While many of these aren't actually hard to program, it can be difficult to find out exactly how. More specifically, this article is on how to link a file extension
(or two, three, four, or five...) to your program and have your application display the appropriate content according to the file.

Background

Take a second to open up Windows Explorer. See all the different types of files (jpg, gif, png, txt, html, etc)? Each one has a different icon and opens with
a certain application when you double click on it. Take a guess, how many lines of code does it take to link your application and an extension? 10? 20? 30?

The answer is 2. Just 2 will do it!

How are programs associated?

The registry stores all the file type-app associations. Click on the Start Menu > Run > Type in 'regedit' > Ok.
Now expand the HKEY_CLASSES_ROOT node. At the top of the window are all the extensions that your computer recognizes. Scroll down to .txt and click on it.
Now look at the default value, it probably is 'txtfile'. Scrolling down the tree on the left, find the txtfile node. This contains all the information about
any extensions that have their default value set to txtfile. Right now, we're just interested in opening the file, so open Shell > Open > Command.
If your .txt files open with notepad, then the default value should be "%SystemRoot%\system32\NOTEPAD.EXE %1".
%SystemRoot% is pretty self-explanatory, it's replaced by the folder that contains system32, which contains NOTEPAD.EXE.
%1 is a command-line argument to pass the the program when a txtfile is opened. %1 is replaced by the file's location.

Step 1: Running your Program when a .Hello File is Opened

The first step is to get your application to open when a chosen extension (like .mp3) is double clicked in Windows Explorer.
For this article, we'll use a file extension that shouldn't exist: .Hello. To use this file type, create a new project called 'Hello World'.
The basic idea is this: a .Hello file contains (in plain text) an adjective. When one is opened, a message box will pop-up and say, "Hello, (file contents) World".
If you open the application manually, it will just say, "Hello, World".

Now we have to edit the registry just like you saw with the .txt extension. In the forms Load event, type the following:

  My.Computer.Registry.ClassesRoot.CreateSubKey(".Hello").SetValue("", "Hello", Microsoft.Win32.RegistryValueKind.String)
  My.Computer.Registry.ClassesRoot.CreateSubKey("Hello\shell\open\command").SetValue("", Application.ExecutablePath & _
  " ""%l"" ", Microsoft.Win32.RegistryValueKind.String)

What does all this do? If you don't understand My.Computer.Registry, here's a link to it on MSDN, otherwise look below:

Code

What it does

CreateSubKey(".Hello")

Creates a registry key in ClassesRoot for the .Hello extension. Notice that you must include the beginning period.

.SetValue("", "Hello"...
  1. "" (Or Nothing) sets the default value of the key.

  2. "Hello" is like the "txtfile" we saw earlier, it tells which registry key contains the information about the .Hello extension.

CreateSubKey("Hello" & _ "\shell\open\command")

This creates the "Hello" sub-key and the "store\open\command" subkey that is needed to store the path to the application that will open this file type.

.SetValue("", Application.ExecutablePath & _ " ""%l"" ",...
  1. Again, "" tells the application to set the key's default value.
  2. Application.ExecutablePath tells the code to associate the currently running executable
    with this file type.
  3. " ""%1"" " passes the opened file's location to your program. The quotes around it are
    optional, but if you have more than one argument, you must put them around each.

Now run your application once. It will edit the registry. Your program is now associated with the .Hello file!

You want to create file association for .txt in your program. You create the file association, but it still opens in Notepad.
What's going on? There is another value that needs to be deleted located here:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt
The value name is 'Progid'. This will consist of a string value of the default program to open this filetype. If this value is present,
you will not be able to associate anything with this particular filetype. You must delete the 'Progid' value in order for the association to work.

Now to test it out. Open Notepad, type in an adjective, and save it as a .Hello file (Make sure you don't accidentally save it as a .Hello.txt file).
Open the file in Windows Explorer. Your program will run! But nothing happens...

Step 2: Reading the File Contents

Now I've told you how to associate the files and the article should be over, right? Nope! This wouldn't be any use if you didn't know how to read the
command-line arguments and finish the program! Luckily, this is simple. My.Application.CommandlineArgs returns a ReadonlyCollection(Of String).


When the registry is set correctly and a file is opened in Windows Explorer, the file's path is pass as a command-line argument
(if you think of an application as a method - a subroutine or function - then these are the parameters).
To retrieve the arguments, you use My.Application.CommandlineArgs. It returns a ReadOnlyCollection(Of String).
You can use My.Application.CommandlineArgs(0) to retrieve the file path, or use the code below to convert the collection to an array.


To convert this to an array (which you don't really need to do unless you're not familiar with working with collecions),
add the following to the Application's Load Event:

  'Array to hold the arguments
  Dim strAllArgs(My.Application.CommandLineArgs.Count - 1) As String
  'Counter Variable
  Dim x as integer = 0

  For Each arg as string In My.Application.CommandLineArgs 
           'Write the arguments to an array
            Try
                strAllArgs(x) = arg
            'Catch Exceptions
            Catch ex As Exception
                strAllArgs(x) = "Could not write argument."
                Debug.Writeline(ex.message)
            End Try
            x += 1
  Next

  If My.Application.CommandLineArgs.Count = 0 Then
            ReDim strAllArgs(0) As String
            strAllArgs(0) = Nothing
  End If

The strAllArgs is the new array.

Now, we have to display the message. More code for the Load event:

  msgbox("Hello, " & My.Computer.FileSystem.ReadAllText(strAllArgs(0)) & " World!")

Screenshot - VBFileAssociation2.gif

Using RegistryActions.FileAssociation

(The easier way)

Okay, now you've done it the hard way, time to learn the easy way. Using the included RegistryActions DLL,
you can associate a file type with a variable and a method. Then, you can read the arguments with just one more method!

Imports RegistryActions.FileAssociation

Public Class HelloForm

    Private ftHello As New FileType(".Hello", "Hello", "Hello World Adjective File", "C:\World.ico")

    Private Sub HelloForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
           DoAssociation.Associate(ftHello, Application.ExecutablePath)
           msgbox("Hello, " & My.Computer.FileSystem.ReadAllText(DoAssociation.WriteCommandsToArray(My.Application.CommandLineArgs)(0)) & " World!")
    End Sub

End Class

See the documentation for more on the RegistryActions Namespace.

Beyond...

Explore the HKEY_CLASSES_ROOT hive. Look for additional features you can add, for example when you right click on a file. Find out how to change the default
icon for a file type... And Keep on Programming!

History

Date Change
4/29/07 Article Submitted
4/30/07
  1. Fixed up article so it fits on one page.
  2. Updated demo project.
5/8/07
  1. Explained My.Application.CommandLineArgs.
6/3/07 Added this tip.
6/8/07 Fixed problems in the DLL.
6/26/07 Changed the wordings in some phrases and fixed some errors in the examples.
6/29/07
  1. Fixed links.
  2. No more sidescrolling!

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

About the Author

Nickr5



Location: United States United States

Other popular VB.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 33 (Total in Forum: 33) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralTHis thing sucksmembersteve ass12:10 18 Jun '08  
GeneralI can't get it workingmembergalaicra13:14 20 Apr '08  
GeneralRe: I can't get it workingmemberNickr56:59 21 Apr '08  
GeneralBug at this versionmemberAdiKL10:46 19 Nov '07  
GeneralCrusial Bug ! at this versionmemberAdiKL10:44 19 Nov '07  
QuestionerrormemberBetaNium6:18 11 Nov '07  
AnswerRe: error [modified]memberNickr57:55 11 Nov '07  
Generalassociat more filesmemberMrRAP9:17 20 Sep '07  
AnswerRe: associat more filesmemberNickr59:45 20 Sep '07  
GeneralRe: associat more filesmemberMrRAP4:47 21 Sep '07  
QuestionIconmemberKschuler7:35 21 Aug '07  
AnswerRe: IconmemberNickr515:39 21 Aug '07  
GeneralRe: IconmemberKschuler3:59 22 Aug '07  
QuestionRe: IconmemberKschuler11:31 29 Aug '07  
GeneralRe: IconmemberNickr515:15 29 Aug '07  
GeneralRe: IconmemberKschuler4:21 30 Aug '07  
GeneralRe: Icon [modified]memberNickr52:23 31 Aug '07  
GeneralRe: IconmemberKschuler3:55 4 Sep '07  
GeneralRe: Icon [modified]memberNickr55:30 4 Sep '07  
Question"Open With" if the program is already runningmemberSchadenfroh13:17 28 Jun '07  
AnswerRe: "Open With" if the program is already runningmembernickr53:02 29 Jun '07  
GeneralAnother waymembersnoopybb11:16 14 Jun '07  
GeneralVery useful!memberTaf Greenstreet9:06 6 Jun '07  
QuestionDoesn't work. ErrorsmemberTanaalethan20:59 31 May '07  
AnswerFixedmembernickr515:21 1 Jun '07  

General General    News News    Question Question    Answer Answer