Public Shared Function OpenFile(ByVal FileToOpen As String, _
ByVal WindowState As Microsoft.VisualBasic.AppWinStyle, _
ByRef ExceptionMessage As String) As Integer
Dim ret As Integer = 0
Dim FileExtension As String = ""
Try
If Not FileToOpen Is Nothing AndAlso FileToOpen.Length > 0 Then
FileExtension = FileToOpen.Substring(FileToOpen.IndexOf("."))
If Not FileExtension Is Nothing AndAlso FileExtension.Length > 0 Then
Dim RegPerm As System.Security.Permissions.RegistryPermission = _
New System.Security.Permissions.RegistryPermission(System.Security.Permissions.RegistryPermissionAccess.Read, "\\HKEY_CLASSES_ROOT")
Dim ClassesRoot As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
Dim TypeKey As Microsoft.Win32.RegistryKey = ClassesRoot.OpenSubKey(FileExtension)
Dim AppFilePath As String = ""
If Not TypeKey Is Nothing Then
Dim FileType As String = TypeKey.GetValue("", "").ToString
If FileType.Length > 0 Then
Dim TypeKey2 As Microsoft.Win32.RegistryKey = ClassesRoot.OpenSubKey(FileType & "\shell\open\command")
If Not TypeKey Is Nothing Then
AppFilePath = TypeKey2.GetValue("", "").ToString
If AppFilePath.Length > 0 AndAlso AppFilePath.ToLower.IndexOf(".exe") > -1 Then
If AppFilePath.StartsWith("""") Then
AppFilePath = AppFilePath.Substring(1)
End If
AppFilePath = AppFilePath.Substring(0, AppFilePath.ToLower.IndexOf(".exe") + ".exe".Length)
If System.IO.File.Exists(AppFilePath) Then
ret = Shell(String.Format("""{0}"" {1}", AppFilePath, FileToOpen), WindowState)
Else
Throw New Exception(String.Format("File does not exist [{0}].", AppFilePath))
End If
Else
Throw New Exception(String.Format("No executable is defined for open command {0}.", AppFilePath))
End If
Else
Throw New Exception(String.Format("No open command is registered for file type {0}.", FileType))
End If
Else
Throw New Exception(String.Format("No file type is registered for extension {0}.", FileExtension))
End If
Else
Throw New Exception(String.Format("No file type is registered for extension {0}.", FileExtension))
End If
Else
Throw New Exception(String.Format("No file extension in args(0) [{0}].", FileToOpen))
End If
Else
Throw New Exception("No file parameter is entered.")
End If
Catch ex As Exception
ret = -1
ExceptionMessage = ex.ToString
End Try
Return ret
End Function
|