[VB.NET]用FindExecutable API取得開啟文件用的執行檔位置
<td valign="top" width="200">指定的檔案不存在</td>
</tr>
<tr>
<td valign="top" width="200">SE_ERR_NOASSOC (31)</td>
<td valign="top" width="200">沒有對應用來開啟的執行檔</td>
</tr>
<tr>
<td valign="top" width="200">SE_ERR_OOM (8)</td>
<td valign="top" width="200">Windows XP only. 系統記憶體資源不足</td>
</tr>
Public Class NoAssociatedFileTypeException Inherits ApplicationException
End Class
Public Class Win32API Const SE_ERR_FNF As Integer = 2 Const SE_ERR_OOM As Integer = 8 Const SE_ERR_NOASSOC As Integer = 31
<Runtime.InteropServices.DllImport("shell32.DLL", EntryPoint:="FindExecutable")> _
Private Shared Function FindExecutable(ByVal lpFile As String, ByVal lpDirectory As String, ByVal lpResult As StringBuilder) As Integer End Function
Public Shared Function GetAssociatedExeFile(ByVal file As String, Optional ByVal throwException As Boolean = True) As String
Dim sb As New StringBuilder(512)
Dim result As Integer = FindExecutable(file, Nothing, sb)
If result > 32 Then
Return sb.ToString
Else
If Not throwException Then
Return String.Empty
End If
Select Case result
Case SE_ERR_FNF
Throw New FileNotFoundException
Case SE_ERR_NOASSOC
Throw New NoAssociatedFileTypeException
Case SE_ERR_OOM
Throw New OutOfMemoryException
End Select
Throw New Exception
End If
End Function
End Class
Public Class NoAssociatedFileTypeException Inherits ApplicationException
End Class
Module FileInfoExtension Const SE_ERR_FNF As Integer = 2 Const SE_ERR_OOM As Integer = 8 Const SE_ERR_NOASSOC As Integer = 31
<Runtime.InteropServices.DllImport("shell32.DLL", EntryPoint:="FindExecutable")> _
Private Function FindExecutable(ByVal lpFile As String, ByVal lpDirectory As String, ByVal lpResult As StringBuilder) As Integer End Function
<Extension()> _
Public Function GetAssociatedExeFile(ByVal fileInfo As FileInfo, Optional ByVal throwException As Boolean = True) As String
Dim sb As New StringBuilder(512)
Dim result As Integer = FindExecutable(fileInfo.FullName, Nothing, sb)
If result > 32 Then
Return sb.ToString
Else
If Not throwException Then
Return String.Empty
End If
Select Case result
Case SE_ERR_FNF
Throw New FileNotFoundException
Case SE_ERR_NOASSOC
Throw New NoAssociatedFileTypeException
Case SE_ERR_OOM
Throw New OutOfMemoryException
End Select
Throw New Exception
End If
End Function
End Module