简体   繁体   中英

Open file from a listbox

I'm trying to open files from a listbox , the files could be Word , PDF , Excel , etc. Does there need to be separate code for each file type, or is there some way to just open the file when its double clicked?

The listbox populates fine through the use of the update button I have.

Public Class frmMain

Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
    Dim folderInfo As New IO.DirectoryInfo("my directory is here")
    Dim arrFilesInFolder() As IO.FileInfo
    Dim fileInFolder As IO.FileInfo
    arrFilesInFolder = folderInfo.GetFiles("*.*")
    For Each fileInFolder In arrFilesInFolder
        ListBox1.Items.Add(fileInFolder.Name)
    Next
End Sub

Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
    Me.Close()
End Sub

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick

End Sub

End Class

In its simplest form you just need to pass the filename to the Process.Start method

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
   Dim fullPath = Path.Combine("YourDirectoryHere", ListBox1.SelectedItem.ToString())
   System.Diagnostics.Process.Start(fullPath)
End Sub

However, this requires that you have saved the directory and recombine it with your file name.

Another problem is the file type (extension) that you try to open. The method that fills the listbox use *.* to load the FileInfo. So every kind of file is added to the listbox and this could be a problem if there is no program associated with that extension.

See more info on Process.Start(string) here

I think what you need is the Win32 API function ShellExecute() : It "opens" files according to their default association in the registry. There's a KB article about how to call ShellExecute from VB.NET .

Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
    Dim fullPath = Path.Combine(("Your file path"), ListBox1.SelectedItem.ToString())
    System.Diagnostics.Process.Start(fullPath)

very easy
note:dont edit the (fullpath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM