Click here to Skip to main content
6,291,124 members and growing! (16,032 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 (VB 8.0, VB 9.0), Windows (WinXP, Vista), .NET (.NET 2.0, .NET 3.0), Visual Studio (VS2005), WinForms, Dev
Version:4 (See All)
Posted:29 Apr 2007
Updated:19 Jun 2009
Views:66,890
Bookmarked:81 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
17 votes for this article.
Popularity: 4.53 Rating: 3.68 out of 5
1 vote, 5.9%
1
3 votes, 17.6%
2
1 vote, 5.9%
3
4 votes, 23.5%
4
8 votes, 47.1%
5

Screenshot - VBFileAssociation1.gif

Introduction

There are many features that every commercial application have, 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 lots 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 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.

Thanks, Computer Masster!

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).

""CommandLineArgs"">My.Application.CommandlineArgs

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 collections), 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

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!
6/19/09 Removed buggy library

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


Member

Location: United States United States

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 40 (Total in Forum: 40) (Refresh)FirstPrevNext
GeneralMailto association Pinmemberasdfasdgf9:25 29 Jun '09  
Questionhow to remove association? PinmemberRathin Mina18:28 18 Mar '09  
GeneralNICE PinmemberMikeDaMan259416:56 14 Jan '09  
GeneralI can't get it working Pinmembergalaicra13:14 20 Apr '08  
GeneralRe: I can't get it working PinmemberNickr56:59 21 Apr '08  
GeneralBug at this version PinmemberAdiKL10:46 19 Nov '07  
GeneralCrusial Bug ! at this version PinmemberAdiKL10:44 19 Nov '07  
Questionerror PinmemberBetaNium6:18 11 Nov '07  
AnswerRe: error [modified] PinmemberNickr57:55 11 Nov '07  
Generalassociat more files PinmemberMrRAP9:17 20 Sep '07  
AnswerRe: associat more files PinmemberNickr59:45 20 Sep '07  
GeneralRe: associat more files PinmemberMrRAP4:47 21 Sep '07  
QuestionIcon PinmemberKschuler7:35 21 Aug '07  
AnswerRe: Icon PinmemberNickr515:39 21 Aug '07  
GeneralRe: Icon PinmemberKschuler3:59 22 Aug '07  
QuestionRe: Icon PinmemberKschuler11:31 29 Aug '07  
GeneralRe: Icon PinmemberNickr515:15 29 Aug '07  
GeneralRe: Icon PinmemberKschuler4:21 30 Aug '07  
GeneralRe: Icon [modified] PinmemberNickr52:23 31 Aug '07  
GeneralRe: Icon PinmemberKschuler3:55 4 Sep '07  
GeneralRe: Icon [modified] PinmemberNickr55:30 4 Sep '07  
AnswerRe: Icon PinmemberMember 441027111:42 8 Jan '09  
Question"Open With" if the program is already running PinmemberSchadenfroh13:17 28 Jun '07  
AnswerRe: "Open With" if the program is already running Pinmembernickr53:02 29 Jun '07  
QuestionRe: "Open With" if the program is already running PinmemberMyplace31110:02 7 Jan '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 19 Jun 2009
Editor: Deeksha Shenoy
Copyright 2007 by Nickr5
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project