Which Program Handles that File Extension?

Wednesday Dec 10th 2003 by Karl Moore

Discover how you can have your Visual Basic programs automatically open files in their default applications for you.

Looking to open a program in its default application? Simply use the Start class and let Windows do the rest of the work for you, like this:

System.Diagnostics.Process.Start( _

But sometimes you want a little more. Sometimes you want to retrieve the exact path to the default program associated with that file type.

With a little rummaging around in the registry, that's exactly what this next code snippet manages to achieve. Simply pass it the file extension, and it'll return the path of the associated application. Passing in the .doc extension on a machine running Office XP, for example, will return the exact path to the Microsoft Word executable.

It's worth noting that this function automatically handles system defined variables, plus removes a number of the excess parameters included in some registry entries. In other words, it works—and well, too, unlike many samples of this technique currently floating around the Internet.

Here's the function:

Public Function GetAssociatedProgram(ByVal FileExtension As _
       String) As String
  ' Returns the application associated with the specified
  ' FileExtension
  ' ie, path\denenv.exe for "VB" files
  Dim objExtReg As Microsoft.Win32.RegistryKey = _
  Dim objAppReg As Microsoft.Win32.RegistryKey = _
  Dim strExtValue As String
      ' Add trailing period if doesn't exist
      If FileExtension.Substring(0, 1) <> "." Then _
          FileExtension = "." & FileExtension
      ' Open registry areas containing launching app details
      objExtReg   = objExtReg.OpenSubKey(FileExtension.Trim)
      strExtValue = objExtReg.GetValue("")
      objAppReg   = objAppReg.OpenSubKey(strExtValue & _
      ' Parse out, tidy up and return result
      Dim SplitArray() As String
      SplitArray = Split(objAppReg.GetValue(Nothing), """")
      If SplitArray(0).Trim.Length > 0 Then
          Return SplitArray(0).Replace("%1", "")
          Return SplitArray(1).Replace("%1", "")
      End If
      Return ""
  End Try
End Function

And here's how you might call it in your application:

Dim strPath As String = GetAssociatedProgram(TextBox1.Text)

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2, $49.99), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

# # #

Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved