Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to open selected files through the default application of the file in VB 2010?

Tags:

vb.net

I have Windows application written in VB 2010.Here, user may select any file from open dialog.So, I want to open the file in corresponding application.for example, suppose user selecting docx file then i have to open the file using msword,suppose,if it is a pdf file, then i have to open with adobe reader or available pdf reader(default application).

Is this possible to do?

like image 253
Saravanan Avatar asked Oct 08 '12 08:10

Saravanan


People also ask

What is file and types in VB?

File I/O Statements. There are three types of file access types in VB 6.0: (a) sequential, (b) random and (c) binary. The default access type is Random, that you should use whenever you read and write variables. Use sequential only to read and write lines.

What is file in Visual Basic?

A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path.


2 Answers

Shell and the Windows API CreateProcess() are for starting executable files. If you're loading a document/file then these are handled by ShellExecute() and can be initiated in .NET using the Process.UseShellExecute property:

Private Function ShellExecute(ByVal File As String) As Boolean
  Dim myProcess As New Process
  myProcess.StartInfo.FileName = File
  myProcess.StartInfo.UseShellExecute = True
  myProcess.StartInfo.RedirectStandardOutput = False
  myProcess.Start()
  myProcess.Dispose()
End Function

Taken from the #VB wiki.

like image 123
Deanna Avatar answered Oct 19 '22 22:10

Deanna


Try this:

now with openfiledialog

Dim OpenFileDlg as new OpenFileDialog.

OpenFileDlg.FileName = "" ' Default file name
OpenFileDlg.DefaultExt = ".xlsx" ' Default file extension
OpenFileDlg.Filter = "Excel Documents (*.XLSX)|*.XLSX"
OpenFileDlg.Multiselect = True
OpenFileDlg.RestoreDirectory = True
' Show open file dialog box
Dim result? As Boolean = OpenFileDlg.ShowDialog()

' Process open file dialog box results
for each path in OpenFileDlg.Filenames
    Try
        System.Diagnostics.Process.Start(Path)

    Catch ex As Exception
        MsgBox("Unable to load the file. Maybe it was deleted?")
    End Try
    If result = True Then
        ' Open document
    Else
        Exit Sub
    End If
next

This will work if the file is registered with the OS. Use Try catch because it can throw errors if the file is in use.

Edit: It uses always the default application.

like image 42
Christian Sauer Avatar answered Oct 19 '22 23:10

Christian Sauer