Determining a File’s Associated Application
FindAssociatedApplication
returns the path to the executable associated with the file passed to the function. An exception is thrown if an error occurs:
Imports System.Text
Private Declare Auto Function FindExecutable Lib "shell32.dll" ( _
ByVal lpFile As String, _
ByVal lpDirectory As String, _
ByVal lpResult As StringBuilder _
) As Int32
Private Const SE_ERR_FNF As Int32 = 2
Private Const SE_ERR_NOASSOC As Int32 = 31
Private Const SE_ERR_OOM As Int32 = 8
Private Const MAX_PATH As Int32 = 260
Private Function FindAssociatedApplication( _
ByVal FileName As String _
) As String
Dim sb As New StringBuilder(MAX_PATH)
Dim n As Int32 = FindExecutable(FileName, vbNullString, sb)
If n > 32 Then
Return sb.ToString()
Else
Dim s As String = "Unknown error."
Select Case n
Case SE_ERR_FNF
s = "File not found."
Case SE_ERR_NOASSOC
s = "No file association found."
Case SE_ERR_OOM ' Since Windows XP.
s = "Out of memory."
End Select
Throw New Exception(s)
End If
End Function
Usage:
Try
MsgBox(FindAssociatedApplication("C:\WINDOWS\WIN.INI"))
MsgBox(FindAssociatedApplication("C:\FOO\FOO.INI"))
Catch ex As Exception
MsgBox(ex.Message)
End Try
FindExecutable
is used for documents, to find the path of an executable file, AssocQueryString
can be used.