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( _ "c:\myfile.doc")
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 = _ Microsoft.Win32.Registry.ClassesRoot Dim objAppReg As Microsoft.Win32.RegistryKey = _ Microsoft.Win32.Registry.ClassesRoot Dim strExtValue As String Try ' 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 & _ "\shell\open\command") ' 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", "") Else Return SplitArray(1).Replace("%1", "") End If Catch Return "" End Try End Function
And here's how you might call it in your application:
Dim strPath As String = GetAssociatedProgram(TextBox1.Text) System.Diagnostics.Process.Start(strPath)
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.
# # #