Introduction
This function returns the EXE filename and the command line for a submitted filename and filename extension. It uses the HKEY_CLASSES_ROOT registry
hive to find the "shell open" program associated with a filename extension.
Using the code
Copy the GetRegisteredApplication
function to your program.
Use the example below to show you how to call GetRegisteredApplication
to retrieve
the EXE associated with the filename extension and the shell commandline.
GetRegistryApplication Function
Imports Microsoft.Win32
Imports System.IO
...
Public Function GetRegisteredApplication( _
ByVal ParamFileName As String, _
ByVal FileExtension As String, _
ByRef AppName As String, _
ByRef ShellAppName As String) As Boolean
Dim strExtension As String
Dim strProgramName As String
Dim strEXEFilename As String
Dim regkey_HKEY_CLASSES_ROOT As RegistryKey
Dim regkey_ProgID As RegistryKey
Dim regkey_OpenCommand As RegistryKey
Dim intIndex As Integer
Try
If FileExtension.StartsWith(".") Then
strExtension = FileExtension
Else
strExtension = "." & FileExtension
End If
Try
regkey_HKEY_CLASSES_ROOT = Registry.ClassesRoot
regkey_ProgID = regkey_HKEY_CLASSES_ROOT.OpenSubKey(strExtension)
strProgramName = regkey_ProgID.GetValue(Nothing).ToString
regkey_ProgID.Close()
Catch
Return False
End Try
Try
regkey_OpenCommand = _
regkey_HKEY_CLASSES_ROOT.OpenSubKey(strProgramName & "\shell\open\command")
strEXEFilename = regkey_OpenCommand.GetValue(Nothing).ToString
regkey_OpenCommand.Close()
Catch
Return False
End Try
intIndex = strEXEFilename.IndexOf(" %1")
If intIndex > 0 Then
strEXEFilename = strEXEFilename.Substring(0, intIndex)
AppName = strEXEFilename
strEXEFilename = strEXEFilename & " " & _
Convert.ToChar(34) & ParamFileName & Convert.ToChar(34)
ShellAppName = strEXEFilename
Else
AppName = strEXEFilename
ShellAppName = strEXEFilename & " " & _
Convert.ToChar(34) & ParamFileName & Convert.ToChar(34)
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
Example
Dim strProgramName As String = ""
Dim strShellCommandLine As String = ""
Dim strTestFileName As String = "C:\windows\CSPU.txt"
If GetRegisteredApplication(strTestFileName, Path.GetExtension(strTestFileName), _
strProgramName, strShellCommandLine) Then
Console.WriteLine("Program Name: " & strProgramName & vbNewLine & _
"Shell CommandLine: " & strShellCommandLine)
Else
MsgBox("Association for " & strTestFileName & _
" was not found.")
End If
Example Results
Program Name: C:\Windows\system32\NOTEPAD.EXE
Shell CommandLine: C:\Windows\system32\NOTEPAD.EXE "C:\windows\CSPU.txt"
History
Version 1: 5 September 2013.